Exercises
For Loops
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Print the numbers 0, 3, 6 and 9 using a single range.
Python
# loop with a step
range takes start, stop and step.
for n in range(0, 10, 3):
print(n)Exercise 2Passed
Print each name and year from the pairs, unpacking in the for line.
Python
pairs = [("Ada", 1815), ("Grace", 1906)]
# print 'Ada: 1815' and so on
Two names in the for line unpack each pair.
pairs = [("Ada", 1815), ("Grace", 1906)]
for name, year in pairs:
print(f"{name}: {year}")Exercise 3Passed
Print 'not in the list' when Alan is not found, without using a flag variable.
Python
names = ["Ada", "Grace"]
for name in names:
if name == "Alan":
print("found")
break
# report not found here
A for loop can have an else that runs only when no break happened.
names = ["Ada", "Grace"]
for name in names:
if name == "Alan":
print("found")
break
else:
print("not in the list")