Chapter 5

Conditionals: if, elif, else

Make decisions in code with if, elif and else branches.

Conditionals let a program choose what to do based on whether a test is True or False. Python uses if, elif and else.

The basic if

An if statement runs its indented block only when its condition is True:

age = 20
if age >= 18:
    print('Adult')

Notice the colon after the condition and the indentation (usually four spaces) of the block. Indentation is how Python knows which lines belong together.

Adding else

else runs when the condition is False:

age = 15
if age >= 18:
    print('Adult')
else:
    print('Minor')

Choosing among many with elif

Use elif (short for else-if) to test more conditions in order. Python stops at the first True branch:

score = 75
if score >= 80:
    print('A')
elif score >= 60:
    print('B')
else:
    print('C')

Here 75 is not at least 80, but it is at least 60, so it prints B.

Combining conditions

Use and, or and not to build bigger tests:

temp = 30
if temp > 20 and temp < 35:
    print('Comfortable')
  • and is True only when both sides are True.
  • or is True when at least one side is True.
  • not flips a value, so not True becomes False.

Nested conditions

You can place an if inside another if to check a second thing only after the first passes:

logged_in = True
is_admin = False
if logged_in:
    if is_admin:
        print('Welcome admin')
    else:
        print('Welcome user')

Truthy and falsy values

An if does not always need a comparison. Some values count as True and some as False on their own. Zero, an empty string and an empty list count as False; most other values count as True:

name = ''
if name:
    print('Has a name')
else:
    print('Name is empty')

This lets you write short, readable checks, such as testing whether the user actually typed something.

Comparing text

Conditions work on strings too, which is useful for menus and answers:

answer = 'yes'
if answer == 'yes':
    print('Great!')
else:
    print('Maybe next time')

Remember that text comparison is case sensitive, so 'Yes' and 'yes' are not equal. Convert with lower() first if you want to accept either.

Remember

  • End every if, elif and else line with a colon.
  • Indent the block that belongs to a condition.
  • Only the first True branch runs; the rest are skipped.

Stuck on this topic? A verified JomKelas tutor can walk you through it.

Find a verified tutor