Variable scope

When writing functions, looping over variables, or writing if statements, we might have variables that are declared within the body of those blocks. For instance, we might have a total variable declared in an if block:
hello = 0
if a == 'hey':
	total = 10
	print(total)        # 10
print(hello, total)   # NameError: name 'total' is not defined
This means that the variable total was declared in the body of an if statement, but is not accessible outside of it.
The same hold for variables declared inside loops or functions:
name = 'Helen'
def greet():
	name = 'Bob'
	print('Hi', name)

greet()                  # Hi Bob
print('Outside:', name)  # Outside: Helen
The variable name is declared in the greet() function and its scope is up until the end of the function. Variables declared within some scope are usually referred to as local variables. As soon as the program exits the function, it “forgets” about that variable.
To access and modify the variables outside of the current scope, we can use the global keyword to tell Python that we would like to treat that variable as global:
name = 'Helen'
def greet():
	global name
	name = 'Bob'
	print('Hi', name)

greet()                  # Hi Bob
print('Outside:', name)  # Outside: Bob
This time the greet() function modified the global name variable and changed its value to Bob. The same global keyword can be used in if statements or loops to refer to global variables.


Given the following function, try to find the mistake and fix it. The function should return the sum of values passed to it so far.
total = 0

def compute_sum(val):
	total = total + val
	return val

To check your solution you need to sign in
Sign in to continue