# Scope

Hey guys, welcome back to the Python basics tutorial! Today you'll learn about the **scope** of variables and functions.

## What's scope?

**Scope** is the area which a variable/function can access. For example, you have probably seen that if you do this:

```python
def myfunc(x, y):
    z = x + y

print(z)
```

It raises a `NameError`, saying that `z` is not defined. Why? `z` IS a regular variable after all!

That's because the variable `z` was defined inside `myfunc`, and therefore only available within it. Its **scope** is limited to `myfunc`. Same for functions too.

{% hint style="info" %}
In case you're wondering, yes, you can define functions inside a function definition too. Go try it out.
{% endhint %}

## Local and Global

As you just saw above, a variable/function which is limited within a specific range is called a **local** variable. And variables defined outside of a code block is **global**, meaning that it can be accessed from any place.

```python
def hello(name):
    reply = 'Hello ' + name # Local variable

name = 'John' # Global
```

You can convert a local variable to a global one too, though you should generally avoid it.

```python
def hello(name):
    reply = 'Hello ' + name

hello('John')
print(name) # Raises NameError

# But, this does not:
def hello(name):
    global reply
    reply = 'Hello ' + name

hello('Mike')
print(reply) # Prints 'Mike'
```

In most cases you'll want to return from the function, not make the variables global.

Hopefully this will solve some of your issues with scope, and you'll see some more tricks in the next few chapters.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://memoryerror.gitbook.io/python-basics/scope.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
