Making Decisions in Python: if, elif, else and Booleans

Python for Beginners: Learn to Code with Real Projects · Python Basics · 6 min read · Updated

A decision

  1. Python starts with a value, for example marks equal to 80.
  2. It checks the first condition. 80 is not at least 90, so the block is skipped.
  3. It checks the next condition from the top. 80 is at least 75, so this block runs.
  4. The matching block gives the result, and the remaining conditions are never checked.

So far your programs ran every line in order. Real programs have to choose: if the marks are high enough, give a pass; if the customer is a member, give a discount; if the file is missing, show a message. In Python, choices are written with if, elif and else, using conditions that are either true or false.

Booleans and comparisons

A boolean has only two values: True and False. You usually get one by comparing things. The comparison operators are == (equal), != (not equal), <, >, <= and >=. Remember: one equals sign stores, two equals signs compare. You can join conditions with and, or and not. and needs both sides true. or needs at least one. not flips the result.

if, elif and else

Read the program below. The block under each if is indented by four spaces. That indentation is how Python knows which lines belong to that choice. The colon at the end of the if line is required.

def grade(marks):
    if marks >= 90:
        return "A"
    elif marks >= 75:
        return "B"
    elif marks >= 50:
        return "C"
    else:
        return "Fail"

for m in [95, 80, 50, 49]:
    print(m, grade(m))

age = 17
has_id = True
if age >= 18 and has_id:
    print("Can enter")
else:
    print("Cannot enter")

# Empty things count as False
name = ""
if not name:
    print("Please enter a name")

# Comparison pitfalls
print(5 == 5.0)
print("5" == 5)
print(1 < 5 < 10)
95 A
80 B
50 C
49 Fail
Cannot enter
Please enter a name
True
False
True
  • Python checks the conditions from the top. The first one that is true runs, and the rest are skipped. That is why the grade function can check >= 90 first and then >= 75: a mark of 80 fails the first and passes the second.
  • elif is short for *else if*. You can have as many as you like, or none.
  • else has no condition. It runs when nothing above was true.
  • A function that returns a value stops at the first return. The grade function uses that, so it does not need extra else blocks.

Truthy and falsy

Python lets you use almost any value as a condition. These count as false: False, None (nothing), 0, 0.0, the empty text "", the empty list [], the empty dictionary {} and the empty set. Everything else counts as true. That is why if not name: is a neat way to say: if the name is empty. It makes checks shorter, but it can hide mistakes when 0 is a valid value, so use if x is None when you mean specifically nothing.

Comparison traps

  • 5 == 5.0 is True, because numbers are compared by value.
  • "5" == 5 is False. Text and number are different kinds of value, and Python does not convert for you. This is why you convert input() first.
  • 1 < 5 < 10 is True. Python allows chained comparisons, which read like maths.
  • Compare text with care: "apple" == "Apple" is False. Use .lower() on both sides when case should not matter.
  • Never compare with == True. Write if is_member: instead.

A real example: a discount rule

Suppose a shop gives 10 percent off if the total is at least 1000, and an extra 5 percent for members. Think about the order and write the rule with plain words first. Then turn it into code.

total = 1500
is_member = True

discount = 0
if total >= 1000:
    discount = 0.10
    if is_member:
        discount += 0.05

final = total * (1 - discount)
print(f"Discount {discount:.0%}, pay {final:.2f}")

This prints Discount 15%, pay 1275.00. Notice the nested if: the member check is inside the first block, so it only runs for orders of 1000 or more. If you wrote the member discount for everyone, the result would be different. Always test the edges: exactly 1000, just below it, a member and a non-member.

Testing your decisions

A good habit is to test each branch of your if with values on both sides of the limit. For the grade function the edges are 90, 89, 75, 74, 50 and 49. The sample program tested 95, 80, 50 and 49. If a decision matters, for example about money, write down the cases and check each one.

Your task

  1. Write age_check.py. Ask for an age, convert it to a number and print child for under 13, teenager for 13 to 17, adult for 18 to 64 and senior for 65 and above.
  2. Add a rule: if the age is below 0 or above 120, print Please check the age and do nothing else.
  3. Test the edge ages 12, 13, 17, 18, 64 and 65.
  4. Rewrite your checks with a chained comparison, such as 13 <= age <= 17.

How to check it worked

  • Ages 12, 13, 17, 18, 64 and 65 give child, teenager, teenager, adult, adult and senior.
  • An age of 150 prints the warning only.
  • You can explain why the order of elif lines matters.

Frequently asked questions

What is the difference between = and ==?

A single = stores a value in a variable. A double == compares two values and gives True or False.

Why does Python care about indentation?

Indentation shows which lines belong to an if, a loop or a function. Use four spaces and keep it consistent.