Variable scopes
A variable scope is simply the part of a program where a variable is accessible. It depends on the place in your code where the variable is created.
Consider the following example:
name = 'Tuna'
def first_function():
print(name)
def second_function():
print(name)
first_function()
second_function()
The output:
Tuna Tuna
As you can see from the output above, both functions printed the same value – Tuna. Notice how the variable name was available to both function, although it was defined outside of them. So the rule is that if a variable is created outside of a function and above it, the function can access it.
Let’s now rewrite our example and create the variable name inside the first_function(). Consider what happens when we run the program:
def first_function():
name = 'Tuna'
print(name)
def second_function():
print(name)
first_function()
second_function()
The output:
>>>
Tuna
Traceback (most recent call last):
File "C:/Users/Antun/Desktop/python new/kod/variable_scope_1.py", line 11, in <module>
second_function()
File "C:/Users/Antun/Desktop/python new/kod/variable_scope_1.py", line 8, in second_function
print(a)
NameError: name 'name' is not defined
>>>
Variables created inside a function are available only to that specific function. That is why, as you can see in the output above, the program returned an error when it tried to print the content of the variable a during the second_function() call.
Consider what happens if we define the variable name outside of a function, and then change its value inside the function definition:
name = 'Tuna' def first_function(): name = 'Maria' print(name) def second_function(): print(name) first_function() second_function()
The output:
>>>
Maria
Tuna
>>>
As you can see from the output above, the first_function() printed the value specified inside the function definition. However, assigning a value to a variable inside a function will not change the variable defined outside that function, although both variables share the same name. That is why second_function() printed the value defined in the main program area.