Programs that choose
Everything you have written so far runs every line, always. Real programs branch: unlock the phone if the passcode matches, otherwise show an error.
Python's if statement runs a block of code only when a condition is True:
age = 20 if age >= 18: print("You are an adult.") else: print("You are a minor.")
The pieces:
ifis followed by a condition, any expression that produces a boolean (lesson 4-1)- The colon
:announces that an indented block follows - The indented lines (4 spaces) are what runs when the condition is
True else:provides the block that runs when it isFalse
Indentation is not decoration in Python. The spaces at the start of a line are how Python knows which lines belong inside the if. Lines indented the same amount form one block.
Code exercise · python
Run the program. Then change age to 15 and run again to watch the other branch fire.
Quiz
In Python, how does the interpreter know which lines belong inside the if branch?
Code exercise · python
Your turn. The variable temperature is 30. Write an if/else: print "hot" if temperature is greater than 25, otherwise print "mild".
A second worked example: the gate everyone uses
Every login screen on earth is, at its core, one if/else: compare what the user typed against the stored secret, and branch. Here it is with input() from lesson 1-3 supplying the condition's left side:
password = input() if password == "open sesame": print("Access granted") else: print("Access denied")
Note the comparison is == (asking, from lesson 4-1), never = (storing). Real systems add one crucial twist — they store a scrambled version of the password rather than the real one — but the branching logic is exactly this.
Code exercise · python
The Input box contains: open sesame. Run it, then change the Input box text to something wrong and run again to see the other branch.