Control Flow: If Statements
Control Flow: If Statements
Programs often need to make decisions. If statements let your code take different paths based on conditions.
Basic If Statement
age = 18
if age >= 18:
print("You are an adult")
The code inside the if block only runs when the condition is True.
If-Else
Handle both cases:
temperature = 72
if temperature > 80:
print("It's hot outside!")
else:
print("The weather is nice.")
If-Elif-Else
Check 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}")
Important: Python checks conditions from top to bottom and stops at the first
Truecondition.
Indentation Matters!
Python uses indentation (spaces) to define code blocks:
if True:
print("This is inside the if block")
print("This too!")
print("This is outside the if block")
Use 4 spaces for indentation (this is the Python standard).
Nested If Statements
You can put if statements inside other if statements:
has_ticket = True
age = 15
if has_ticket:
if age >= 13:
print("Enjoy the movie!")
else:
print("Sorry, this movie is PG-13")
else:
print("Please buy a ticket first")
Combining Conditions
Use and, or, and not to combine conditions:
age = 25
has_license = True
has_car = False
# Need both license AND car to drive
if has_license and has_car:
print("You can drive!")
else:
print("You can't drive right now")
# Can vote if 18 or older
if age >= 18:
print("You can vote")
# Check if NOT a minor
if not age < 18:
print("You're an adult")
Common Patterns
Checking for empty values
name = ""
if name:
print(f"Hello, {name}!")
else:
print("Name is empty")
Checking membership
fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("We have bananas!")
Practice Problem
Write a program that checks if a number is positive, negative, or zero:
number = -5
if number > 0:
print("Positive")
elif number < 0:
print("Negative")
else:
print("Zero")