Exercises
Break and Continue
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Print the first name starting with G, then stop looking.
Python
names = ["Ada", "Grace", "Georgia"]
# print only the first G name
break leaves the loop as soon as you have what you need.
names = ["Ada", "Grace", "Georgia"]
for name in names:
if name.startswith("G"):
print(name)
breakExercise 2Passed
Skip the blank rows and the comment rows, and print the rest split on the comma.
Python
rows = ["", "ada,36", "# a comment", "grace,45"]
for row in rows:
# skip what you do not want, then print
passcontinue is a guard clause for loops, and keeps the real work unindented.
rows = ["", "ada,36", "# a comment", "grace,45"]
for row in rows:
if not row:
continue
if row.startswith("#"):
continue
name, age = row.split(",")
print(name, age)Exercise 3Passed
Find the target in the grid and return its row and column, or None. break alone cannot leave both loops.
Python
def find(grid, target):
# return (row, col) or None
pass
print(find([[1, 2], [3, 4]], 4))
print(find([[1, 2], [3, 4]], 9))return leaves both loops and the function at once.
def find(grid, target):
for r, row in enumerate(grid):
for c, value in enumerate(row):
if value == target:
return r, c
return None
print(find([[1, 2], [3, 4]], 4))
print(find([[1, 2], [3, 4]], 9))