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
totalvariable declared in an
hello = 0 if a == 'hey': total = 10 print(total) # 10 print(hello, total) # NameError: name 'total' is not defined
This means that the variable
totalwas declared in the body of an
ifstatement, but is not accessible outside of it.
The same holds for variables declared inside loops or functions:
name = 'Helen' def greet(): name = 'Bob' print('Hi', name) greet() # Hi Bob print('Outside:', name) # Outside: Helen
nameis 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
globalkeyword 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
namevariable and changed its value to
Bob. The same
globalkeyword can be used in
ifstatements 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 print(compute_sum(10)) print(compute_sum(20)) print(compute_sum(30))