The nuances of working with scopes in Python
Let's consider the important nuances of working with local and global variables.
Let's say we have a global variable num. Let's create a function func that will print the global num to the console:
num = 1
def func():
print(num)
func() # 1
Now let's declare a local num on the line below the print function. After executing the code, an error will be printed to the console. This happens because Python inside the function perceives num only as a local variable that has not yet been declared:
num = 1
def func():
print(num) # error num = 2
Let's now rewrite the code inside the function so that the value of the variable num increases by 2:
num = 1
def func():
num += 2 # will display an error
The error is caused by the fact that the expression num += 2 is written as follows:
num = num + 2
However, the local variable to which the addition occurs has not yet been declared. And accordingly, Python displays an error, since it is impossible to add a number to a non-existent value.
What will be the result of running the following code:
tst = '12'
def func():
tst = 12
return tst
print(tst)
What will be the result of running the following code:
tst = 'abc'
def func():
tst = tst.upper()
return tst
func()
print(tst)
What will be the result of running the following code:
tst = 'abc'
def func():
txt = tst.upper()
return txt
print(func())
print(tst)