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 and execute different code depending on conditions. Python uses if, elif, and else for branching logic.
The simplest form checks one condition:
temperature = 35
if temperature > 30:
print("It's hot outside!")
The code inside the if block runs only when the condition is True. Python uses indentation (four spaces by convention) to define blocks — there are no curly braces.
Add an else branch for the case when the condition is false:
age = 16
if age >= 18:
print("You can vote.")
else:
print("You are too young to vote.")
Use elif (short for "else if") to test multiple conditions:
score = 78
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}")
Python checks conditions from top to bottom and executes the first branch whose condition is True. Once a match is found, the rest are skipped.
In Python, values that are considered false in a boolean context (falsy) include:
Everything else is truthy:
name = ""
if name:
print(f"Hello, {name}")
else:
print("No name provided") # this runs
You can nest if statements inside other blocks:
is_logged_in = True
is_admin = False
if is_logged_in:
if is_admin:
print("Welcome, admin!")
else:
print("Welcome, user!")
else:
print("Please log in.")
Python has a one-line conditional expression:
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # adult
username = "alice"
password = "secret123"
if username == "alice" and password == "secret123":
print("Login successful")
else:
print("Invalid credentials")
Mastering control flow is essential — virtually every real program makes decisions based on data. Practice writing conditions that are clear and readable.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.