Variable Scope in Function Definition Statements


What is the scope of a variable introduced in a function definition "def" statement block in Python?



Any new variables introduced in a function statement block is valid only in that statement block. In other words, the scope of a local variable in a function is limited to the function only.

Also note that variables introduced outside the function statement block are not available to the statement block. In other words, each function statement block maintains it own local variable list independent of the parent statement blocks.

Here is a good demonstration of local variables limited to the scope of the function statement block.

>>> legalAge = 18
>>> def profile(name,age=legalAge+3):
...     print("Name: "+name)
...     print("Age: "+str(age))
...     print(str('legalAge' in locals()))
...     legalAge = 20
...     print("Local Legal Age: "+str(legalAge))
...     drikingAge = 21
...     print("Drinking Age introduced: "+str(drikingAge))
>>> profile("Joe")
Name: Joe
Age: 21
Local Legal Age: 20
Drinking Age introduced: 21
>>> legalAge
>>> 'drinkingAge' in locals()

The output shows:

  • The local variable "legalAge" is independent of the variable outside the function of the same name.
  • The local variable "drikingAge" is out of scope after the execution of the function.


Defining Functions in Python

⇒⇒Python Tutorials

2017-09-12, 110👍, 0💬