4. Elif
elif adds more conditions to an if chain:
elifmeans "else if". It has its own condition and a colon.- Python checks the conditions from top to bottom. An
elifis tested only when all the previous conditions wereFalse. - The first condition that is
Truewins: its block runs and the rest of the chain is skipped. elseis optional. When present, it runs only when every condition isFalse.
Grade a score
Create a variable score with the value 85. Use an if/elif/else chain:
score >= 90printsAscore >= 80printsB- otherwise, print
C
Only the first true condition runs.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Child, teen or adult
Read an age with input("Age: ") and convert it with int(). Use a single if/elif/else chain to print:
Childwhen the age is less than13Teenwhen the age is less than18Adultotherwise
The simulated user types 15.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
The first match wins
Create a variable temperature with the value 25. Print:
Warmwhentemperature >= 25Mildwhentemperature >= 15Coldotherwise
25 satisfies both of the first two conditions. Only the first match runs.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Match a color
Create a variable color with the value "yellow". Print:
Stopwhencoloris"red"Waitwhencoloris"yellow"Gowhencoloris"green"Unknownfor anything else
Print exactly:
Create a free account to save your progress and unlock chapter 2.