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")
                                    
if
Check
else
Otherwise
elif
More Options

Lesson 1: Your First If Statement

Let's start with simple yes/no decisions:

Basic If Statement
# 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 Comparisons
# 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:

If-Else Examples
# 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
# 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 Advice
# 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:

Using 'and' - Both must be true
# 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")
Using 'or' - At least one must be true
# 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")
Using 'not' - Reverse the condition
# 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:

Nested If Example
# 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 Game Example
# 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:

Simple Calculator
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)

๐Ÿง  Test Your Knowledge

Which symbol checks if two values are equal?

What does 'elif' mean?

Which operator means "both conditions must be true"?