Lessons / Python / Unit 2

Making decisions

if lets your program choose what to do. In Python, the spaces at the start of a line decide which code belongs to which if.

Python · Unit 2 of 5 · about 4 minutes

True and False

A comparison gives back True or False. In Python they start with a capital letter.

print(5 > 3)
print(5 < 3)
print(4 == 4)
print(4 != 4)
True
False
True
False

== checks if two values are the same. != checks if they're different. A single = stores a value, so don't use it to compare.

Try it

What does this print?

print(3 == "3")
One is a number and the other is a string, so they aren't equal.

if and indentation

An if line ends with a colon. The lines that belong to it are indented, usually by four spaces. When the indenting stops, you're back outside the if.

temp = 30

if temp > 25:
    print("It's hot")
print("Done")
It's hot
Done

Try it

What happens when this runs?

if 5 > 2:
print("yes")
The print line belongs to the if, so it has to be indented. Without the spaces, Python stops before running anything.

elif and else

elif is short for else if. Python checks each condition from the top and runs the first one that's true. else catches everything left over.

score = 72

if score >= 90:
    print("A")
elif score >= 70:
    print("B")
else:
    print("Keep practising")
B

Try it

What does this print?

n = 7

if n > 10:
    print("big")
elif n > 5:
    print("medium")
else:
    print("small")
7 isn't greater than 10. It is greater than 5, so medium prints and the else is skipped.

and, or, not

Python uses plain words to combine conditions. and needs both sides true. or needs at least one. not flips the result.

age = 15
has_ticket = True

if age >= 13 and has_ticket:
    print("You can go in")
You can go in

Common mistakes

Forgetting the colon

if score > 50 with no colon at the end gives a SyntaxError.

Writing true instead of True

Lowercase true isn't a Python value. You'll get NameError: name 'true' is not defined.

Mixing tabs and spaces

Lines can look lined up but still be different to Python. Use four spaces everywhere and let your editor handle it.

Recap

  • Comparisons give True or False.
  • if, elif and else lines end with a colon.
  • Indented lines belong to the if above them.
  • and, or and not combine conditions.