What You Will Learn
Programs need to make decisions. If it is raining, take an umbrella. If the score is high enough, you win. This lesson teaches you how to control what code runs depending on conditions.
The if Statement
age = 18
if age >= 18:
print("You are an adult.")
Expected output:
You are an adult.
The code inside the if block only runs if the condition is True. Notice the colon after the condition and the indentation (4 spaces) before print. Indentation is how Python knows which code belongs inside the if.
The else Clause
else runs when the condition is False:
age = 15
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
Expected output:
You are a minor.
The elif Clause
elif (short for “else if”) checks another condition if the first one was False:
score = 75
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")
Expected output:
Grade: C
Python checks each condition in order and runs the first one that is True. Once a match is found, the rest are skipped.
Comparison Operators
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | x == 5 |
!= | Not equal to | x != 5 |
> | Greater than | x > 5 |
< | Less than | x < 5 |
>= | Greater than or equal | x >= 5 |
<= | Less than or equal | x <= 5 |
Combining Conditions
Use and, or, and not to combine conditions:
age = 25
has_licence = True
if age >= 18 and has_licence:
print("You can drive.")
temperature = 22
if temperature > 30 or temperature < 0:
print("Extreme weather!")
else:
print("Normal temperature.")
is_raining = False
if not is_raining:
print("No umbrella needed.")
Expected output:
You can drive.
Normal temperature.
No umbrella needed.
A Real Example
print("=== Password Checker ===")
password = input("Enter a password: ")
if len(password) < 8:
print("Too short. Must be at least 8 characters.")
elif len(password) < 12:
print("Acceptable password.")
else:
print("Strong password!")
Example interaction:
=== Password Checker ===
Enter a password: hello
Too short. Must be at least 8 characters.
What You Learned
ifruns code only when a condition isTrueelseruns when the condition isFalseelifchecks additional conditions- Use
and,or,notto combine conditions - Indentation defines which code belongs to each block
In the next lesson, you will learn how to repeat actions with for loops.