chapter 4.1

Control Flow

Making decisions with conditionals

So far, your code runs top to bottom, every line, every time. Conditionals let your code make decisions — run this block *only if* something is true.
temperature = 35

if temperature > 30:
    print("It's hot outside!")
else:
    print("It's nice out.")
warning
Indentation matters! The indented lines under if and else are the body of each branch. Python uses indentation (4 spaces) instead of braces {} like other languages.
Use elif (short for "else if") to check multiple conditions in order:
score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"

print(f"Score: {score} → Grade: {grade}")
Comparison operators return True or False:
info
== equal to | != not equal to
> greater than | < less than
>= greater or equal | <= less or equal
Logical operators combine conditions:
age = 25
has_id = True

if age >= 21 and has_id:
    print("Access granted")

temperature = 15
if temperature < 0 or temperature > 40:
    print("Extreme weather!")
else:
    print("Weather is fine")

is_raining = False
if not is_raining:
    print("No umbrella needed")
You can nest conditionals, but keep it readable — if you're more than 2-3 levels deep, there's probably a cleaner way:
logged_in = True
is_admin = False

if logged_in:
    if is_admin:
        print("Welcome, admin")
    else:
        print("Welcome, user")
else:
    print("Please log in")
your turn
challenge

Build a grading system: given a `score` variable, print the grade (A/B/C/D/F) with a message. Use `elif` for each threshold and an f-string for the output.

loading editor...

output
$ Press RUN to execute your code
AI Tutor

Ask about Control Flow

Hey! I'm your AI tutor.

Ask me anything about this lesson, or paste code you're stuck on.

AI tutor is a premium feature