Python If...Else Statements
Learn to make decisions in your Python programs
๐ค Making Decisions in Code
If...else statements help your program make choices! Just like in real life, you check if something is true, then decide what to do. Think of it like: "If it's raining, take an umbrella. Otherwise, don't."
# Simple decision making
age = 18
if age >= 18:
print("You can vote!")
else:
print("Too young to vote")
Lesson 1: Your First If Statement
Let's start with simple yes/no decisions:
# Check if someone is tall enough for a ride
height = 150 # in centimeters
if height >= 140:
print("๐ข You can ride the roller coaster!")
print("Have fun!")
print("Thanks for visiting!")
# This will print:
# ๐ข You can ride the roller coaster!
# Have fun!
# Thanks for visiting!
# Different ways to compare things
score = 85
name = "Alice"
is_sunny = True
# Check if score is high
if score > 90:
print("Excellent score!")
# Check if names match
if name == "Alice":
print("Hello Alice!")
# Check boolean values
if is_sunny:
print("It's a sunny day!")
# Check if something is NOT true
if not is_sunny:
print("It's not sunny today")
๐ก Comparison Symbols:
-
==Equal to (Are they the same?) -
!=Not equal to (Are they different?) -
>Greater than -
<Less than -
>=Greater than or equal -
<=Less than or equal
Lesson 2: If-Else (Two Choices)
Sometimes you want to do one thing if true, and something different if false:
# Check if someone can drive
age = 16
if age >= 18:
print("๐ You can get a driver's license!")
else:
print("๐ You need to wait a bit longer")
years_left = 18 - age
print(f"Wait {years_left} more years")
# Check if a number is even or odd
number = 7
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")
# Simple password check
correct_password = "secret123"
user_password = input("Enter password: ")
if user_password == correct_password:
print("โ
Welcome! You're logged in!")
else:
print("โ Wrong password. Try again.")
Lesson 3: Multiple Choices with elif
When you have more than two options, use
elif
(else if):
# Grade calculator
score = 87
if score >= 90:
grade = "A"
print("๐ Excellent work!")
elif score >= 80:
grade = "B"
print("๐ Good job!")
elif score >= 70:
grade = "C"
print("โ
You passed!")
elif score >= 60:
grade = "D"
print("๐ Need to study more")
else:
grade = "F"
print("โ Failed - Please retake")
print(f"Your grade is: {grade}")
# Weather-based clothing advice
temperature = 22 # in Celsius
if temperature > 30:
print("๐ It's hot! Wear shorts and a t-shirt")
elif temperature > 20:
print("๐ค๏ธ Nice weather! Light clothes are perfect")
elif temperature > 10:
print("๐งฅ A bit cool. Wear a jacket")
elif temperature > 0:
print("๐งฃ Cold! Wear warm clothes")
else:
print("๐ฅถ Freezing! Bundle up!")
Logical Operators
Combine multiple conditions using logical operators:
and Operator
Both conditions must be true
or Operator
At least one condition must be true
not Operator
Reverses the boolean value
Lesson 4: Combining Conditions (and, or)
Sometimes you need to check multiple things at once:
# Check if someone can drive
age = 17
has_license = True
if age >= 16 and has_license:
print("๐ You can drive!")
else:
print("๐ซ You cannot drive yet")
# Movie ticket pricing
age = 12
is_student = True
if age < 18 and is_student:
print("๐ฌ Student discount: $8")
elif age < 18:
print("๐ฌ Child price: $10")
else:
print("๐ฌ Adult price: $15")
# Check if it's a weekend
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("๐ It's the weekend! Time to relax!")
else:
print("๐ผ It's a weekday. Time to work!")
# Check if you need an umbrella
is_raining = False
is_sunny = True
if is_raining or is_sunny:
print("โ๏ธ You might want to bring something!")
else:
print("๐ค๏ธ Perfect weather, no accessories needed")
# Check if game is over
is_game_over = False
if not is_game_over:
print("๐ฎ Keep playing! Game is still running")
else:
print("๐ Game Over!")
# Check if user is logged in
is_logged_in = False
is_admin = False
if not is_logged_in:
print("๐ Please log in to continue")
elif not is_admin:
print("โ ๏ธ You need admin rights for this")
else:
print("โ
Welcome admin!")
Lesson 5: If Inside If (Nested)
You can put if statements inside other if statements for more complex decisions:
# Amusement park ride checker
age = 12
height = 130 # in cm
if age >= 8:
print("โ
Age requirement met")
if height >= 120:
print("โ
Height requirement met")
print("๐ข You can ride the roller coaster!")
else:
print("โ Too short for this ride")
print(f"You need to be at least 120cm tall")
else:
print("โ Too young for this ride")
print("Try the kiddie rides instead!")
# Simple number guessing game
secret_number = 7
guess = 5
if guess == secret_number:
print("๐ Congratulations! You guessed it!")
else:
print("โ Wrong guess!")
if guess < secret_number:
print("๐ Your guess is too low")
else:
print("๐ Your guess is too high")
print("Try again!")
Practice Project: Simple Calculator
Let's build a simple calculator that makes decisions based on user input:
def simple_calculator():
"""A simple calculator using if-else statements"""
print("๐งฎ Simple Calculator")
print("=" * 20)
# Get numbers from user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
# Get operation
print("\nChoose operation:")
print("1. Add (+)")
print("2. Subtract (-)")
print("3. Multiply (*)")
print("4. Divide (/)")
choice = input("Enter choice (1/2/3/4): ")
# Perform calculation based on choice
if choice == "1":
result = num1 + num2
print(f"\n{num1} + {num2} = {result}")
elif choice == "2":
result = num1 - num2
print(f"\n{num1} - {num2} = {result}")
elif choice == "3":
result = num1 * num2
print(f"\n{num1} ร {num2} = {result}")
elif choice == "4":
if num2 != 0:
result = num1 / num2
print(f"\n{num1} รท {num2} = {result}")
else:
print("\nโ Error: Cannot divide by zero!")
else:
print("\nโ Invalid choice! Please choose 1, 2, 3, or 4")
# Run the calculator
simple_calculator()
Common Mistakes to Avoid
๐ซ Using = instead of ==
Wrong:
if age = 18:
Right:
if age == 18:
Remember: = assigns a value, == compares values
๐ซ Forgetting the colon :
Wrong:
if age >= 18
Right:
if age >= 18:
Always end if statements with a colon!
๐ซ Wrong indentation
Wrong:
if age >= 18:
print("You can vote")
Right:
if age >= 18:
print("You can vote")
Code inside if statements must be indented (4 spaces)