Learn Python if/else statements through real-world examples and simple illustrations. Master conditional logic to make your Python programs smart and interactive.
๐ 6 min read
Hey there! Welcome back to our Python journey. ๐
Remember when we learned about variables and data types? Well, today we’re going to make our programs smart by teaching them how to make decisions!
Think about your daily life:
Python’s if/else statements work exactly the same way. Let me show you how simple and powerful they are!
Let’s start with a simple real-world example:
# Simple analogy: Deciding what to wear
weather = "rainy"
if weather == "rainy":
print("Take an umbrella! โ")
else:
print("Enjoy the sunshine! โ๏ธ")
What’s happening here?
We check if the weather is “rainy”
If true, Python runs the indented code below
If false, it runs the code under else
๐ฆ Traffic Light Analogy Think of if/else statements like traffic lights:
light_color = "red"
if light_color == "red":
print("๐ STOP!")
elif light_color == "yellow":
print("โ ๏ธ SLOW DOWN!")
else: # green light
print("โ
GO!")
Comparison Operators: The Decision Tools Before we dive deeper, let’s understand the tools Python uses to make comparisons:
age = 25
if age == 25: # True
print("You're 25 years old!")
if age != 30: # True
print("You're not 30 years old")
if age > 18: # True
print("You're an adult")
if age < 65: # True
print("You're not a senior yet")
if age >= 21: # True
print("You can drink in the US")
if age <= 25: # True
print("You're 25 or younger")
Multiple Conditions with Elif What if we have more than two options? Enter elif (short for “else if”):
score = 85
if score >= 90:
grade = "A"
message = "Excellent! ๐"
elif score >= 80:
grade = "B"
message = "Great job! ๐"
elif score >= 70:
grade = "C"
message = "Good work! ๐"
elif score >= 60:
grade = "D"
message = "You passed! โ
"
else:
grade = "F"
message = "Let's practice more! ๐"
print(f"Grade: {grade} - {message}")
Important: Python checks conditions from top to bottom and stops at the first true condition!
Logical Operators: Combining Conditions Sometimes you need to check multiple things at once:
age = 16
has_money = True
if age >= 13 and has_money:
print("You can buy a movie ticket! ๐ฌ")
day = "saturday"
is_holiday = True
if day == "saturday" or day == "sunday" or is_holiday:
print("It's the weekend! Time to relax! ๐๏ธ")
is_raining = False
if not is_raining:
print("Perfect day for a walk! ๐ถ")
Real-World Example: Movie Ticket System Let’s build a complete movie ticket system:
print("=== Welcome to Python Cinema ===")
age = int(input("How old are you? "))
has_money = input("Do you have money? (yes/no) ").lower() == "yes"
is_weekend = input("Is it weekend? (yes/no) ").lower() == "yes"
if age < 5:
print("๐ฌ Free ticket for little ones!")
elif age < 13:
print("๐ฌ Child ticket: $8")
elif age >= 65:
print("๐ฌ Senior discount: $10")
else:
print("๐ฌ Adult ticket: $12")
if has_money:
print("๐ฐ You can purchase snacks!")
else:
print("๐ธ Maybe just enjoy the movie!")
if is_weekend:
print("๐ Weekend surcharge applies (+$2)")
Your Turn: Practice Exercise Try this simple game - a number guessing challenge:
import random
secret_number = random.randint(1, 10)
print("๐ฏ I'm thinking of a number between 1 and 10!")
# Get user's guess
guess = int(input("What's your guess? "))
if guess == secret_number:
print("๐ Amazing! You guessed it!")
elif guess > secret_number:
print("๐ Too high! Try a lower number.")
print(f"The secret number was {secret_number}")
else:
print("๐ Too low! Try a higher number.")
print(f"The secret number was {secret_number}")
Challenge: Modify this game to give the user 3 tries to guess the number!
Common Mistakes to Avoid
if age == 25
print("You're 25!")
if age == 25:
print("You're 25!")
2. Using = Instead of ==
if age = 25:
print("You're 25!")
if age == 25:
print("You're 25!")
if age > 18:
print("You're an adult") # Missing indentation
if age > 18:
print("You're an adult") # Proper indentation
if condition1:
if condition2:
if condition3:
print("This is confusing!")
if condition1 and condition2 and condition3:
print("Much clearer!")
Advanced Example: Smart Weather Advisor Let’s build something really useful:
print("๐ค๏ธ Smart Weather Advisor")
temperature = int(input("What's the temperature? (ยฐF) "))
is_raining = input("Is it raining? (yes/no) ").lower() == "yes"
is_weekend = input("Is it weekend? (yes/no) ").lower() == "yes"
print("\n๐ก My recommendations:")
if temperature > 85:
print("โข Stay hydrated! ๐ง")
print("โข Wear light clothing ๐")
elif temperature > 60:
print("โข Perfect weather! ๐")
print("โข Great for outdoor activities ๐ด")
else:
print("โข Bundle up! ๐งฅ")
print("โข Hot drink weather โ")
if is_raining:
print("โข Don't forget your umbrella! โ")
print("โข Perfect movie day ๐ฌ")
else:
print("โข No umbrella needed! ๐")
print("โข Great for a walk ๐ถ")
if is_weekend and not is_raining and temperature > 60:
print("โข Perfect for a picnic! ๐งบ")
print("โข Maybe visit the park ๐ณ")
Debugging Tips
Problem: My if/else statement isn't working!
Solution:
Check your colons :
Verify indentation (4 spaces)
Use print() to see variable values
Test each condition separately
age = 25
print(f"Debug: age = {age}") # See the actual value
if age == 25:
print("Condition is true!")
else:
print("Condition is false!")
What’s Next? Python Loops! In our next post, we’ll learn about loops - how to make Python repeat tasks for you! We’ll cover:
for loops for repeating tasks a specific number of times
while loops for repeating until a condition changes
Building a number guessing game with unlimited tries
Automating repetitive tasks
Your Mission Create a “Restaurant Order System” that:
Asks for the customer’s age
Asks what they want to order
Suggests drinks based on age (alcohol for 21+, soda for others)
Applies discounts for seniors (65+)
Shows a custom message based on their order
Bonus: Add a loyalty program check and apply points!
Wrapping Up Today you learned how to make your Python programs smart! You can now:
โ Use if, elif, and else statements
โ Compare values using operators
โ Combine conditions with and, or, not
โ Build interactive programs that make decisions
โ Avoid common beginner mistakes
Remember: Programming is about solving real problems. Every time you write an if/else statement, you’re teaching your program to think!
Practice makes perfect - try modifying the examples, break them, fix them, and create your own decision-making programs!
Happy coding! ๐
Stuck on any of the examples? Have a cool if/else project you built? Share in the comments below! I’d love to see what you create.
Comments & Discussion
Join the conversation using your GitHub account. Comments are powered by Utterances.