Python variables scope

When you declare a variable, that variable is visible in parts of your program, depending on where you declare it.

If you declare it outside of any function, the variable is visible to any code running after the declaration, including functions:

age = 8

def test():
    print(age)

print(age) # 8
test() # 8

We call it a global variable.

If you define a variable inside a function, that variable is a local variable, and it is only visible inside that function. Outside the function, it is not reachable:

def test():
    age = 8
    print(age)

test() # 8

print(age)
# NameError: name 'age' is not defined


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com

When you declare a variable, that variable is visible in parts of your program, depending on where you declare it.

If you declare it outside of any function, the variable is visible to any code running after the declaration, including functions:

age = 8

def test():
    print(age)

print(age) # 8
test() # 8

We call it a global variable.

If you define a variable inside a function, that variable is a local variable, and it is only visible inside that function. Outside the function, it is not reachable:

def test():
    age = 8
    print(age)

test() # 8

print(age)
# NameError: name 'age' is not defined


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com


Print Share Comment Cite Upload Translate Updates
APA

flaviocopes.com | Sciencx (2021-01-03T05:00:00+00:00) Python variables scope. Retrieved from https://www.scien.cx/2021/01/03/python-variables-scope/

MLA
" » Python variables scope." flaviocopes.com | Sciencx - Sunday January 3, 2021, https://www.scien.cx/2021/01/03/python-variables-scope/
HARVARD
flaviocopes.com | Sciencx Sunday January 3, 2021 » Python variables scope., viewed ,<https://www.scien.cx/2021/01/03/python-variables-scope/>
VANCOUVER
flaviocopes.com | Sciencx - » Python variables scope. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/01/03/python-variables-scope/
CHICAGO
" » Python variables scope." flaviocopes.com | Sciencx - Accessed . https://www.scien.cx/2021/01/03/python-variables-scope/
IEEE
" » Python variables scope." flaviocopes.com | Sciencx [Online]. Available: https://www.scien.cx/2021/01/03/python-variables-scope/. [Accessed: ]
rf:citation
» Python variables scope | flaviocopes.com | Sciencx | https://www.scien.cx/2021/01/03/python-variables-scope/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.