Course outline · 0% complete

0/27 lessons0%

Course overview →

if and else

lesson 4-2 · ~13 min · 13/27

Programs that choose

Everything you have written so far runs every line, always. Real programs branch: unlock the phone if the passcode matches, and 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:

  • if is followed by a condition, any expression that produces a boolean as in lesson 4-1
  • The colon : announces that an indented block follows
  • The indented lines, conventionally 4 spaces, are what runs when the condition is True
  • else: provides the block that runs when it is False

Indentation is not decoration in Python. The spaces at the start of a line are how Python knows which lines belong inside the if, and lines indented the same amount form one block. Most languages use curly braces for this and treat indentation as a courtesy to readers. Python made the courtesy the rule, which is why Python code from different authors tends to look alike.

age >= 18 ?TrueFalse"adult" block"minor" blockexactly one branch runs
An if/else is a fork in the road: the condition picks which one of the two blocks runs. Never both.

One condition, one branch taken

The condition is True, so the first block runs and the second does not.

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

Output

You are an adult.

Only one of the two print lines can ever run on a given execution. Setting age to 15 would produce the other line and never both.

That exclusivity is the guarantee else gives you, and it is stronger than writing two separate if statements. With if age >= 18: followed by if age < 18:, nothing structurally prevents both from running if you later get one of the conditions wrong.

How Python knows which lines are inside the if

The lines inside are the ones indented underneath the if line.

Indentation defines blocks in Python. Every line indented under the if, conventionally by 4 spaces, is inside it, and the block ends where the indentation returns to the previous level.

Wrong indentation changes what the program means rather than just how it looks. A print that should be inside the if runs unconditionally if you un-indent it, with no error to warn you.

One practical consequence: never mix tabs and spaces in the same file. They can look identical on screen while Python counts them differently, producing an inconsistent-indentation error that is genuinely hard to see.

A temperature branch

With temperature at 30, the condition holds and the first block runs.

temperature = 30
if temperature > 25:
    print("hot")
else:
    print("mild")

Output

hot

Reading the pieces

  • The if line ends in a colon, and its block is indented beneath it. The else: line returns to the outer indentation level, which is how Python knows the first block has ended.
  • The condition uses > rather than >=, so a temperature of exactly 25 would print mild. Boundary values are worth checking deliberately, because both operators look reasonable in the source.
  • Nothing here has to be a variable. if 30 > 25: would work identically and be useless, since the value that varies is the whole reason the branch exists.

Checking a typed password

The condition compares the typed line against the expected string.

password = input()
if password == "open sesame":
    print("Access granted")
else:
    print("Access denied")

The comparison uses ==, the asking operator from lesson 4-1, and never =, the storing operator. This is the situation where mixing them up is most tempting, and most consequential.

Real systems add one crucial twist: they store a scrambled version of the password rather than the real one, so a stolen database does not hand over everyone's password. The branching logic, though, is exactly this shape, comparing what was typed against what was stored.

The password check running

Given the correct phrase on standard input, the first branch runs.

password = input()
if password == "open sesame":
    print("Access granted")
else:
    print("Access denied")

Input

open sesame

Output

Access granted

The condition compares the typed string to "open sesame" character by character, so any difference at all makes it False. That includes capitalization, a trailing space, or two spaces between the words.

String equality being this literal is what makes it useful for a password and annoying for a username. Systems that want to be forgiving have to do the forgiving themselves, usually by lowercasing both sides before comparing.