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")
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")
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")
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
if score > 50 with no colon at the end gives a SyntaxError.
Lowercase true isn't a Python value. You'll get NameError: name 'true' is not defined.
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.