You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Control flow lets your program make decisions. Instead of running every line from top to bottom, your code can choose different paths based on conditions. The if, elif, and else statements are the foundation of decision-making in Python.
if StatementThe simplest form of a conditional — run a block of code only if a condition is True:
age = 18
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 runs.
Key syntax:
:if...elseProvide an alternative path when the condition is False:
temperature = 35
if temperature > 30:
print("It's hot outside!")
else:
print("The weather is pleasant.")
if...elif...elseUse elif (short for "else if") for multiple conditions:
score = 75
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: C
Important: Python checks each condition from top to bottom and executes the first block whose condition is True. Once a match is found, the remaining conditions are skipped.
These operators return True or False:
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | 5 == 5 → True |
!= | Not equal to | 5 != 3 → True |
< | Less than | 3 < 5 → True |
> | Greater than | 5 > 3 → True |
<= | Less than or equal | 5 <= 5 → True |
>= | Greater than or equal | 5 >= 3 → True |
Combine multiple conditions with and, or, and not:
and — Both conditions must be Trueage = 25
has_ticket = True
if age >= 18 and has_ticket:
print("You can enter the concert.")
or — At least one condition must be Trueday = "Saturday"
if day == "Saturday" or day == "Sunday":
print("It's the weekend!")
not — Reverses a booleanis_raining = False
if not is_raining:
print("Let's go for a walk!")
age = 25
income = 50000
has_good_credit = True
if (age >= 21 and income >= 30000) or has_good_credit:
print("Loan approved!")
Use parentheses to make the logic clear.
In Python, every value can be evaluated as True or False:
# Falsy values — evaluate to False
if not 0: print("0 is falsy")
if not 0.0: print("0.0 is falsy")
if not "": print("Empty string is falsy")
if not []: print("Empty list is falsy")
if not {}: print("Empty dict is falsy")
if not None: print("None is falsy")
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.