# Python variables scope

> Understand variable scope in Python and the difference between global and local variables, including why accessing a local variable outside raises a NameError.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2021-01-03 | Topics: [Python](https://flaviocopes.com/tags/python/) | Canonical: https://flaviocopes.com/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:

```python
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:

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

test() # 8

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