🐍beginner
Python If/Else — Making Decisions in Code
Learn how Python makes choices using if, elif, and else — the building blocks of smart programs that react to different situations.
Programs That Think
Every day, you make tons of decisions: 'If it's raining, I'll take an umbrella. Otherwise, I'll wear sunglasses.' Your brain checks a condition (is it raining?) and does different things based on the answer.
Python works the exact same way! With if/else statements, your code can check conditions and decide what to do. This is what makes programs smart — they don't just do the same thing every time, they react to different situations.
Your First If Statement
python
age = 12
if age >= 13:
print("You can create a social media account!")
else:
print("You're not old enough yet.")
print(f"Wait {13 - age} more year(s)!")
# Output:
# You're not old enough yet.
# Wait 1 more year(s)!How It Works
Here's the recipe:
1. if — checks a condition (is something true?)
2. The condition — a question that's either True or False (like age >= 13)
3. Colon : — always put this after the condition
4. Indented code — the lines underneath that are pushed right (4 spaces) ONLY run if the condition is True
5. else: — what happens if the condition is False
The indentation (those 4 spaces) is super important in Python. It's how Python knows which code belongs inside the if and which code is outside it.
Multiple Conditions with elif
python
# elif = "else if" — check another condition
score = 75
if score >= 90:
grade = "A — Amazing!"
elif score >= 80:
grade = "B — Great job!"
elif score >= 70:
grade = "C — Not bad!"
elif score >= 60:
grade = "D — Keep trying!"
else:
grade = "F — Let's study more!"
print(f"Score: {score} => {grade}")
# Score: 75 => C — Not bad!Comparison Operators
python
# These are the tools you use to compare things:
x = 10
y = 20
print(x == y) # False (equal to?)
print(x != y) # True (not equal to?)
print(x > y) # False (greater than?)
print(x < y) # True (less than?)
print(x >= 10) # True (greater than or equal?)
print(x <= 5) # False (less than or equal?)
# Combine conditions with 'and' / 'or'
age = 12
has_ticket = True
if age >= 10 and has_ticket:
print("You can ride the rollercoaster!")
if age < 5 or age > 65:
print("You get a discount!")Pro Tip
Common mistake: using = instead of ==. A single = means 'set this value' (assignment). A double == means 'check if these are equal' (comparison). So 'if score = 100' will crash, but 'if score == 100' works perfectly.
Try It Yourself
Build a ticket price calculator! Ask the user for their age using input(). If they're under 5, it's free. Ages 5-12 cost $8. Ages 13-17 cost $12. Adults 18-64 cost $15. Seniors 65+ cost $10. Print the price with a friendly message.
Ready to build?
Put what you learned into practice — pick a project and start coding.
Start Building Free