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
More python tutorials:
- Introduction to Python
- Installing Python 3 on macOS
- Running Python programs
- Python 2 vs Python 3
- The basics of working with Python
- Python Data Types
- Python Operators
- Python Strings
- Python Booleans
- Python Numbers
- Python, Accepting Input
- Python Control Statements
- Python Lists
- Python Tuples
- Python Sets
- Python Dictionaries
- Python Functions
- Python Objects
- Python Loops
- Python Modules
- Python Classes
- The Python Standard Library
- Debugging Python
- Python variables scope
- Python, accept arguments from command line
- Python Recursion
- Python Nested Functions
- Python Lambda Functions
- Python Closures
- Python Virtual Environments
- Use a GoPro as a remote webcam using Python
- Python, how to create a list from a string
- Python Decorators
- Python Docstrings
- Python Introspection
- Python Annotations
- Python, how to list files and folders in a directory
- Python, how to check if a number is odd or even
- Python, how to get the details of a file
- Python, how to check if a file or directory exists
- Python Exceptions