Python, lesson 4
So far every line of your programs has run. Real programs need to choose: charge shipping
only on small orders, warn only when the battery is low. Python's tool for this is if.
The line ending in a colon is the condition. The indented block under it runs only when
the condition is true. Indentation is not decoration in Python: it is how the language knows
which lines belong to the if. Use four spaces per level.
Add elif ("else if") for more cases and else for "anything else". Python checks the
conditions from top to bottom and runs only the first block whose condition is true.
Because the checks happen in order, the second test doesn't need to say speed <= 120; if
that were false, Python would never have reached it.
2 exercises to try what you just read.
| Operator | Means |
|---|---|
== | equal to |
!= | not equal to |
< > | less / greater than |
<= >= | less / greater or equal |
Each comparison produces a bool. Don't mix up = (store a value) with == (compare two
values).
Python lets you chain comparisons the way you would write them in maths:
0 <= age < 18 means 0 <= age and age < 18.
Strings compare too: "apple" < "banana" is True because comparison goes character by
character. Uppercase letters sort before lowercase ones, so normalise case first if it matters.
and is true when both sides are true.or is true when at least one side is true.not flips true and false.The membership test in is often clearer than a chain of or: if day in ("Sat", "Sun"):.
Python treats some values as false in a condition even though they aren't False: zero,
empty strings, empty collections and None. Everything else counts as true. So
if name: means "if the name isn't empty".
When you just need to pick one of two values, a conditional expression is shorter:
For comparing one value against several fixed options, match reads nicely. case _:
catches anything left over, and | means "or":
Read a whole-number temperature in °C and print one word:
FreezingColdMildHotSample input:
Sample output:
A year is a leap year if it divides by 4, except years that divide by 100, which are leap years only if they also divide by 400. So 2024 and 2000 are leap years, 1900 is not.
Read a year and print leap or common.
Sample input:
Sample output:
battery = int(input())
if battery < 20:
print("Battery low, plug in soon.")
print("Status checked.")speed = int(input())
if speed > 120:
print("Way too fast")
elif speed > 90:
print("A bit fast")
else:
print("Fine")if age >= 18 and has_ticket:
print("Come in")
if day == "Sat" or day == "Sun":
print("Weekend!")label = "even" if n % 2 == 0 else "odd"match command:
case "start" | "go":
print("Starting")
case "stop":
print("Stopping")
case _:
print("Unknown command")18Mild2024leap