Making decisions
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Making a choice
ifruns some code only when a condition is true.- The condition is followed by a colon
:. - The lines that belong to the
ifare indented (4 spaces).
Comparisons
- A condition is usually a comparison that is True or False.
==equal,!=not equal,<><=>=.- Note:
==tests equality; a single=stores a value.
temperature = 30
if temperature > 25:
print("It is hot.")
if / elif / else
elif("else if") checks another condition if the first was false.elseruns when none of the conditions were true.- Python checks them in order and stops at the first true one.
hour = 14
if hour < 12:
print("Morning")
elif hour < 18:
print("Afternoon")
else:
print("Evening")
Combine conditions
andis true only when both sides are true.oris true when at least one side is true.notflips true to false and false to true.
day = "Sat"
if day == "Sat" or day == "Sun":
print("Weekend!")
In Cambridge pseudocode
- Python
if/elif/elsematches the exam'sIF … ELSE … ENDIFandCASE.
IF score >= 50 THEN
OUTPUT "Pass"
ELSE
OUTPUT "Fail"
ENDIF
CASE OF grade
"A": OUTPUT "Top"
"B": OUTPUT "Good"
OTHERWISE: OUTPUT "Keep trying"
ENDCASE
Now you try
- The checks type the input for you. Read it, then decide what to print.
- Match the output text exactly.
Read a score with int(input()). Print Pass if it is 50 or more, otherwise print Fail. For input 72, print Pass.
Click Run to see the output here.
Read a score. Print A if it is 80+, B if it is 60+, otherwise C. Use if / elif / else. For input 75, print B.
Click Run to see the output here.
Read an age. Print Yes if the age is from 13 to 19 (a teenager), otherwise No. Use and. For input 16, print Yes.
Click Run to see the output here.