Exercises
Global Variables
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
bump() should change the global count. Make it work without changing the prints.
Python
count = 0
def bump():
count += 1
bump()
bump()
print(count)Declare the name global at the top of the function.
count = 0
def bump():
global count
count += 1
bump()
bump()
print(count)Exercise 2Passed
record() appends to the global list. It needs no global keyword — add only the append.
Python
scores = []
def record(value):
# add value to scores
pass
record(10)
record(20)
print(scores)Changing an object in place is not rebinding the name.
scores = []
def record(value):
scores.append(value)
record(10)
record(20)
print(scores)Exercise 3Passed
Rewrite this to pass the value in and hand the result back, with no global at all.
Python
count = 0
def bump():
global count
count += 1
bump()
bump()
print(count)Give bump a parameter and return the new value.
def bump(value):
return value + 1
count = 0
count = bump(count)
count = bump(count)
print(count)