Conditionals
Conditionals let your code make decisions based on whether something is true or false.
The if Statement
age = 18
if age >= 18:
print("You can vote!")
Note: the indented code only runs when the condition is True.
if / else
temperature = 35
if temperature > 90:
print("It's hot!")
else:
print("It's not too bad.")
if / elif / else
Use elif (short for "else if") to check multiple conditions:
grade = 85
if grade >= 90:
print("A")
elif grade >= 80:
print("B")
elif grade >= 70:
print("C")
else:
print("Keep trying!")
Tip: Python checks conditions top to bottom and stops at the first match.
Comparison Operators
| Operator | Meaning |
|---|---|
== | equal to |
!= | not equal to |
< | less than |
> | greater than |
<= | less than or equal to |
>= | greater than or equal to |
name = "Alex"
if name == "Alex":
print("Hey Alex!")
Logical Operators
Combine conditions with and, or, and not:
age = 16
has_permit = True
if age >= 16 and has_permit:
print("You can drive!")
if age < 13 or age > 65:
print("Discount available!")
if not has_permit:
print("Get a permit first.")
Nested Conditionals
You can put conditionals inside other conditionals:
is_member = True
age = 15
if is_member:
if age < 18:
print("Junior member discount!")
else:
print("Member discount!")
else:
print("Sign up for discounts!")
Common Mistakes
Using = instead of ==
# Wrong - this assigns, doesn't compare
if score = 100:
# Right - this compares
if score == 100:
Forgetting the colon
# Wrong
if age > 18
print("Adult")
# Right
if age > 18:
print("Adult")
Incorrect indentation
# Wrong - print is not indented
if age > 18:
print("Adult")
# Right
if age > 18:
print("Adult")