Flow controls: Conditions · 6 / 22 Theory

Common mistakes with conditions

Conditions are simple, but they have traps that almost everybody falls into at first. These are the most common mistakes and how to avoid them.

1. Using = instead of ==

= assigns and == compares. Python protects you from this mistake:

x = 5
if x = 5:      # SyntaxError: invalid syntax
    print("five")

2. Forgetting the colon

if x > 3        # SyntaxError: expected ':'
    print("greater")

3. Wrong indentation

if x > 3:
print("greater")   # IndentationError: expected an indented block

And the subtlest one: a line outside the block when you wanted it inside, or the other way round. The program does not fail, but it does something else.

4. Comparing text with a number

input() always returns text. If you compare it with a number it will never be equal:

n = input()
if n == 5:               # always False: "5" is not 5
    print("five")

n = int(input())
if n == 5:               # correct
    print("five")

And if you compare two texts with < or >, they are compared alphabetically: "10" < "9" is True. Convert to int or float first.

5. Upper and lower case

answer = input()
if answer == "yes":                # fails with "Yes" or "YES"
    print("Accepted")

if answer.lower() == "yes":         # better
    print("Accepted")

6. The or mistake

day = input()
if day == "saturday" or "sunday":      # always True
    print("Weekend")

if day == "saturday" or day == "sunday":   # correct
    print("Weekend")

7. Impossible conditions or the wrong order

If one condition already includes the following ones (x > 0 before x > 100), the later ones will never run. Order from the most restrictive to the most general, as you saw with elif.

8. Comparing decimals with ==

print(0.1 + 0.2 == 0.3)            # False
print(abs(0.1 + 0.2 - 0.3) < 1e-9)  # True: compare with a tolerance

Checklist

  • Do the if, elif and else end in :?
  • Is the whole block indented the same?
  • Am I comparing with == and not =?
  • Am I comparing numbers with numbers and texts with texts?
  • Are the elif ordered from most to least restrictive?

Practice with Student grade evaluation, where the order of the conditions is key.