Python is popular because it reads almost like English. You can run every example here in a free online editor or after installing Python from python.org.
Variables and types
name = "Asha" # text (str)
age = 24 # whole number (int)
score = 91.5 # decimal (float)
is_enrolled = True # True or False (bool)
print(name, age) # Asha 24
Lists
skills = ["SQL", "Excel"]
skills.append("Python")
print(skills[0]) # SQL
print(len(skills)) # 3
Making decisions
if score >= 90:
print("Grade A")
elif score >= 75:
print("Grade B")
else:
print("Keep practicing")
Loops
for skill in skills:
print("I know", skill)
total = 0
for n in range(1, 6): # 1, 2, 3, 4, 5
total += n
print(total) # 15
Functions
def average(numbers):
return sum(numbers) / len(numbers)
print(average([80, 90, 100])) # 90.0
Tip: Python uses indentation (four spaces) to group code inside if statements, loops and functions. Mixed indentation is the most common beginner error.
Practice
Print only the even numbers from 1 to 10.
for n in range(1, 11):
if n % 2 == 0:
print(n)