Unit 2 ยท Lesson 2

if / else

Until now, every line of your code ran in order, top to bottom. That changes right now. With if and else, your programs learn to choose.

Write your first if statement
Use else for the alternate path
Understand indentation rules
Combine conditions with %

Your First if Statement

An if statement checks a condition. If it's True, the indented code runs. If it's False, Python skips it entirely.

age = 20 if age >= 18: print("You can vote!") print("Program continues...")

Let's break down the syntax โ€” there are three crucial parts:

1. The keyword if โ€” tells Python a decision is coming.
2. The condition โ€” any expression that evaluates to True or False (like the ones from Lesson 2.1!).
3. The colon : โ€” don't forget it! This marks the start of the indented block.

The Power of Indentation

Python uses indentation (4 spaces) to know which lines belong to the if block. Everything indented runs only when the condition is True:

temperature = 35 if temperature > 30: print("It's hot outside!") # โ† inside the if block print("Stay hydrated!") # โ† also inside print("Have a nice day!") # โ† outside โ€” always runs
โš ๏ธ IndentationError: If you forget to indent after the colon, or mix tabs and spaces, Python will throw an error. The code editor here uses 4 spaces for you, but watch out in other editors!

Adding else

What if you want to do something different when the condition is False? That's what else is for:

age = 15 if age >= 18: print("Welcome in!") else: print("Sorry, you must be 18+.")

Think of it like a fork in the road โ€” your code always takes one path or the other, never both:

age >= 18 ?
True โ†“
"Welcome in!"
False โ†“
"Sorry, 18+."
Key rule: else never has a condition โ€” it catches everything that didn't match the if. And it also needs a colon!

Storing Results from Branches

A common pattern is to set a variable inside the branches:

score = 72 if score >= 60: result = "Pass" else: result = "Fail" print(f"Score: {score} โ€” {result}") # Score: 72 โ€” Pass

This works because exactly one branch always runs, so result is always defined by the time we reach the print().

The Modulo Trick

Remember the % operator from Unit 1? It returns the remainder after division. Combined with if, it's incredibly useful:

number = 7 if number % 2 == 0: print(f"{number} is even") else: print(f"{number} is odd")
Why this works: Any even number divided by 2 has a remainder of 0. So number % 2 == 0 is True for even numbers and False for odd numbers. You'll use this pattern constantly!
Practice Time

Challenges

๐Ÿšช

Challenge 1: The Bouncer

Guided

You're the bouncer at a club. Check the patron's age and set the right message.

Instructions: Write an if/else statement:
โ€ข If age is 21 or older โ†’ set message to "Welcome in!"
โ€ข Otherwise โ†’ set message to "Come back when you're 21."
Hint 1: Start with if age >= 21: then indent the next line to set message.
Hint 2: Don't forget the else: on its own line, followed by an indented line setting the other message.
Hint 3:
if age >= 21:
    message = "Welcome in!"
else:
    message = "Come back when you're 21."
๐Ÿ”ข

Challenge 2: Even or Odd

Guided

Use the modulo operator to classify a number as even or odd.

Instructions: Write an if/else using the % operator:
โ€ข If number is even โ†’ set parity to "even"
โ€ข Otherwise โ†’ set parity to "odd"
Hint 1: A number is even if number % 2 == 0. That's your condition!
Hint 2: if number % 2 == 0: then set parity to "even" in the indented block.
๐Ÿ“‹

Challenge 3: Pass or Fail

Solo

Determine if a student passed or failed based on their score, and build a result message.

Instructions:
โ€ข If score is 60 or higher โ†’ set result to "Pass"
โ€ข Otherwise โ†’ set result to "Fail"
โ€ข Then create report as an f-string: "Score: 73 โ€” Pass" (using the actual score and result)
Hint 1: First write the if/else to set result. Then on a new line (not indented inside either block), create the report.
Hint 2: The report format is: f"Score: {score} โ€” {result}". Note the em-dash (โ€”), not a hyphen.
Hint 3: Make sure the report line is outside the if/else, at the same indentation level as the if keyword.
๐Ÿงฎ

Challenge 4: Build Your Own abs()

Stretch

Python has a built-in abs() function, but can you build one yourself with just if/else?

Instructions: Given a number, create a variable absolute that holds its absolute value (always positive):
โ€ข If the number is negative โ†’ set absolute to number * -1
โ€ข Otherwise โ†’ set absolute to number as-is

Do NOT use the built-in abs() function! The point is to build the logic yourself.
Hint 1: A number is negative if number < 0. To make it positive, multiply by -1.
Hint 2: If the number is already positive (or zero), you don't need to change it at all.
Hint 3:
if number < 0:
    absolute = number * -1
else:
    absolute = number