Lesson 4

Conditionals — making decisions

Run different code depending on whether something is true. The pattern: if, optionally elif, optionally else.

The basic shape

age = 20

if age >= 18:
    print("You're an adult.")
else:
    print("You're a minor.")

Three things to notice:

Indentation matters in Python Other languages use { } to group code. Python uses indentation. Be consistent — use 4 spaces (most editors will do this when you press Tab).

elif — more than two branches

score = 72

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

print(f"Grade: {grade}")
Grade: C

Python checks each condition top to bottom and runs the first one that's true.

Combining conditions: and, or, not

age = 22
has_ticket = True

if age >= 18 and has_ticket:
    print("Welcome in.")

if age < 18 or not has_ticket:
    print("Sorry, can't enter.")

Truthiness

Python is generous about what counts as "true" in a condition. These are all falsy:

Everything else is "truthy". So you can write nice short checks:

name = input("Name? ")

if name:                       # True if name is not empty
    print(f"Hi {name}")
else:
    print("You didn't enter a name.")

A small worked example

password = input("Pick a password: ")

if len(password) < 8:
    print("Too short — at least 8 characters please.")
elif password.lower() == password:
    print("Add at least one uppercase letter.")
else:
    print("Looks good!")
Quick recap if runs a block when something is true. elif adds more branches. else is the fallback. Combine conditions with and, or, not.