6. Conditionals

Conditionals

Real programs must make decisions: show a discount only to members, warn when a battery is low, mark an answer right or wrong. Python makes decisions with the if statement, which runs a block of code only when a condition is true.

The basic if statement

Write the keyword if, a condition, and a colon. The code that runs when the condition is true is indented underneath. Indentation (usually four spaces) is how Python knows which lines belong to the block; it is not optional:

PYTHON
temperature = 38
if temperature > 37.5:
    print("You may have a fever.")
▸ OUTPUT
You may have a fever.

else and elif

Add else for what to do when the condition is false, and elif (short for "else if") to test further conditions in order. Python checks each condition from top to bottom and runs the first block whose condition is true, then skips the rest:

PYTHON
score = 72
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"
print(grade)
▸ OUTPUT
C
score >= 90 ? grade = A score >= 80 ? score >= 70 ? grade = C else: grade = F True False

Comparison and logical operators

Conditions are built from comparisons that produce True or False. The comparison operators are == (equal), != (not equal), <, >, <=, and >=. Note the double equals for comparison; a single = is assignment. Combine conditions with the logical operators and, or, and not:

PYTHON
age = 20
has_ticket = True
if age >= 18 and has_ticket:
    print("Entry allowed.")
if not has_ticket:
    print("Please buy a ticket.")
▸ OUTPUT
Entry allowed.

and is true only when both sides are true; or is true when at least one side is true; not flips a value.

Truthiness

Every value in Python can be treated as true or false in a condition. Zero, empty strings, empty lists, and None are "falsy"; almost everything else is "truthy". This lets you write natural checks:

PYTHON
name = input("Name? ")
if name:
    print(f"Hi, {name}")
else:
    print("You did not enter a name.")
▸ OUTPUT (user pressed Enter without typing)
Name?
You did not enter a name.

Nesting

An if can live inside another if. Increase the indentation for each level, but avoid nesting too deeply because it quickly becomes hard to read:

PYTHON
logged_in = True
is_admin = False
if logged_in:
    if is_admin:
        print("Welcome, admin.")
    else:
        print("Welcome, user.")
▸ OUTPUT
Welcome, user.

Conditionals give your programs the power of choice. Practice by writing a program that reads a number and prints whether it is negative, zero, or positive using if, elif, and else.