Making Decisions with If/Else
Control the flow of your program by making decisions based on conditions.
Prerequisites
So far, our programs run every line from top to bottom. But real programs need to make decisions: "if this is true, do that; otherwise, do something else." This is called conditional execution.
The if Statement
age = 20
if age >= 18:
print("You are an adult")
print("You can vote")
print("This always runs")Output:
You are an adult
You can vote
This always runsKey things to notice:
- The condition (age >= 18) is followed by a colon :
- The indented lines only run if the condition is True
- Indentation matters! Python uses it to know what's inside the if
- The non-indented line runs regardless of the condition
if/else
Use else to specify what happens when the condition is False:
age = 15
if age >= 18:
print("You are an adult")
else:
print("You are a minor")Output: "You are a minor"
if/elif/else
Use elif (short for "else if") for multiple conditions:
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Your grade is {grade}") # Your grade is BPython checks conditions from top to bottom and runs the first matching block. Once a condition matches, it skips the rest.
Nested Conditionals
You can put if statements inside other if statements:
has_ticket = True
age = 15
if has_ticket:
if age >= 18:
print("Welcome to the R-rated movie")
else:
print("Sorry, you must be 18+")
else:
print("Please buy a ticket first")Combining Conditions
Use and, or, and not to build complex conditions:
age = 25
has_license = True
is_sober = True
if age >= 16 and has_license and is_sober:
print("You can drive")
else:
print("You cannot drive")
# Using 'or'
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("It's the weekend!")
# Using 'not'
is_raining = False
if not is_raining:
print("No umbrella needed")Truthy and Falsy Values
Python treats some values as "falsy" (act like False) and others as "truthy" (act like True):
# Falsy values: False, 0, 0.0, "", [], {}, None
# Everything else is truthy
name = ""
if name:
print(f"Hello, {name}")
else:
print("Name is empty") # This runs
count = 0
if count:
print("Count has a value")
else:
print("Count is zero") # This runsPractice
- Write a program that checks if a number is positive, negative, or zero
- Create a simple calculator that asks for two numbers and an operation (+, -, *, /)
- Write a program that determines if a year is a leap year
- Create a "guess the number" game that tells the user if their guess is too high, too low, or correct