Making decisions with if
So far every line runs. With if, your program can choose.
temp = 31
if temp > 30:
print("Hot!")
elif temp > 15:
print("Nice.")
else:
print("Jacket time.")
How it works: Python checks the conditions from top to bottom and runs the block under the first one that is true. Then it skips the rest. elif (short for "else if") and else are optional, and you can have as many elifs as you like. So with temp = 31, only "Hot!" prints, even though 31 is also greater than 15.
Two details that matter:
- The line ends with a colon
:. - The code inside is indented (4 spaces is the standard). Indentation is not decoration in Python; it is how Python knows which lines belong to the
if. Get it wrong and you get anIndentationError, or worse, code that runs at the wrong time.
Comparison operators give you True or False:
==equal,!=not equal<><=>=
Classic mistake: = assigns, == compares. if score = 10: is a syntax error.
Combine conditions with and, or and not:
if age >= 13 and age <= 19:
print("teen")
Python even lets you write that as 13 <= age <= 19, which reads like maths.
Strings can be compared too: "cat" == "Cat" is False, because case counts. Lowercasing first with .lower() is the usual fix.
Try it yourself
Edit it. Break it. Run it again.score = 74
if score >= 90:
grade = "A"
elif score >= 70:
grade = "B"
elif score >= 50:
grade = "C"
else:
grade = "try again"
print(f"{score} gets {grade}")
answer = "YES"
if answer.lower() == "yes" and score > 50:
print("Both conditions are true")
print(10 == 10, 3 != 3, 5 <= 4)
Your turn
Type it yourself. That is the whole trick.1Even or odd
Read a whole number. Print even if it is even and odd if it is not. With the input 17 the output is odd.
The checker feeds this input to your program.
n = int(input())
print("even")
2Ride check
A ride needs riders to be at least 140 cm tall and under 200 cm. Read a height (whole number). Print You can ride if both rules are met, Too short if the height is under 140, and Too tall otherwise. With the input 200 the output is Too tall.
The checker feeds this input to your program.
height = int(input())
if height >= 140:
print("You can ride")