Exercises
Scope
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
bump should change the module-level count. Make it work.
Python
count = 0
def bump():
count += 1
bump()
print(count)Declare the name global inside the function.
count = 0
def bump():
global count
count += 1
bump()
print(count)Exercise 2Passed
Make the counter remember its own count between calls.
Python
def make_counter():
count = 0
def increment():
count += 1
return count
return increment
counter = make_counter()
print(counter(), counter(), counter())The name lives in the enclosing function, not the module.
def make_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
counter = make_counter()
print(counter(), counter(), counter())Exercise 3Passed
This shadows the builtin sum. Rename the local so the builtin stays available.
Python
def total(numbers):
sum = 0
for n in numbers:
sum += n
return sum
print(total([1, 2, 3]))
print(sum([1, 2, 3]))Name it after what it holds, such as running_total.
def total(numbers):
running_total = 0
for n in numbers:
running_total += n
return running_total
print(total([1, 2, 3]))
print(sum([1, 2, 3]))