Exercises
If...Else
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Print Can vote when age is 18 or over, and Too young otherwise.
Python
age = 15
# print the right message
if, a condition, a colon, then an indented block; else for the other case.
age = 15
if age >= 18:
print("Can vote")
else:
print("Too young")Exercise 2Passed
The grades come out wrong because the conditions are in the wrong order. Fix it so 95 gives A.
Python
score = 95
if score >= 50:
grade = "C"
elif score >= 90:
grade = "A"
else:
grade = "F"
print(grade)Only the first true branch runs, so the narrowest condition must come first.
score = 95
if score >= 90:
grade = "A"
elif score >= 50:
grade = "C"
else:
grade = "F"
print(grade)Exercise 3Passed
Rewrite the nested ifs as three early returns.
Python
def describe(age):
if age < 0:
return "not a real age"
else:
if age < 18:
return "minor"
else:
return "adult"
print(describe(-1), describe(10), describe(30))Handle each exceptional case and return; leave the main path at the bottom.
def describe(age):
if age < 0:
return "not a real age"
if age < 18:
return "minor"
return "adult"
print(describe(-1), describe(10), describe(30))