Skip to content

If Statements

if statements let you branch out based on the outcome of a boolean test.

Code blocks

Code blocks are a group of one or more statements that are meant to be executed as a unit. They are used to define the body of conditional statements, loops, functions and classes.

Python uses indentation to define code blocks and they have the following shape:

  • the block definition statement must end with a colon (:)
  • the block's body must be indented to the right by one space or more (4 spaces is the recommended amount). The indentation must be consistent for the entire block.
  • the block ends when the indentation returns to the previous level.

if — single branching

Executes the block only if the test condition is True, and does nothing otherwise.

>>> temp = 32
>>> if temp > 30:
...    print("It's hot")
...    print("Drink water")
...
It's hot
Drint water

if - elif - else - multiple branching

Evaluate multiple test conditions and execute the block of the first "true" branch. The else clause runs if no other branch evaluated to True.

>>> score = 75
>>> if score >= 90:
...    grade = "A"
... elif score >= 80:
...    grade = "B"
... elif score >= 70:
...    grade = "C"
... else:
...    grade = "F"
...
>>> print(grade) 
C

Order matters

Put the most specific / highest conditions first when there is overlap. In the previous example, if score >=70 were put first, everybody with a score greater than 70 would get a grade of "C", making the "A" and "B" grades unattainable!

Ternary operator

You can use if - else to write expressions that return a value of any type based on a boolean expression

>>> height = int(input("Enter height in centimeters: "))
Enter height: 130
>>> "Tall" if height > 160 else "Short"
'Short'

Example

# ticket.py
age = int(input("Enter your age: "))
if age < 0:
    print("Invalid age")
elif age < 5:
    print("Free")
elif age < 18 or age >= 65:
    print("Discounted: $8")
else:
    print("Full price: $12")