Tools, FAQ, Tutorials:
Variable Scope in Function Definition Statements
What is the scope of a variable introduced in a function definition "def" statement block in Python?
✍: FYIcenter.com
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))
... drinkingAge = 21
... print("Drinking Age introduced: "+str(drinkingAge))
...
>>> profile("Joe")
Name: Joe
Age: 21
False
Local Legal Age: 20
Drinking Age introduced: 21
>>> legalAge
18
>>> 'drinkingAge' in locals()
False
The output shows:
⇒ Function Parameters Assigned with Object References
⇐ Function Parameter Default Expression Executed Only Once
2022-10-26, ∼2642🔥, 0💬
Popular Posts:
How to use the API operation 2017 version setting "Rewrite URL template"? The API operation setting ...
How to use the XML to JSON Conversion Tool at freeformatter.com? If you want to try the XML to JSON ...
What is EPUB 3.0 Metadata "dc:publisher" and "dc:rights" elements? EPUB 3.0 Metadata "dc:publisher" ...
Where Is the Submitted Form Data Stored in PHP? When a user submit a form on your Web server, user e...
How to extend json.JSONEncoder class? I want to encode other Python data types to JSON. If you encod...