Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
What are scopes? | Scopes
Mastering Python: Closures and Decorators
course content

Course Content

Mastering Python: Closures and Decorators

What are scopes?

The scope is an environment that stores variables, functions, and other objects in a program.

Let's consider the example:

The number variable in the regular code and the number in the some_function have the same name but are different variables because they are placed in different scopes.

Scope Types

  • Built-in
  • Global
  • Non-local (Enclosing)
  • Local

Built-in Scope

This is a scope of Python built-in tools. For example, the built-in len() function. You can use this function everywhere in your code.

Global Scope

It's the main scope of your code. This scope contains the variables, functions, and other objects you define.

Non-local (Enclosing) Scope

The non-local scopes are scopes between global and local scopes. The non-local scope can be enclosed and transformed into the enclosing scope. It will be described in the next section.

Local Scope

This scope is used for functions. Every function has a unique scope that deletes after the function executes.

How do scopes work?

Let's take a look at an example and analyze it.:

Here the global scope has the variables number and string and the add() function.
The len() and print() functions are used from the built-in scope.
The add() function has a local scope with the variables first, second, and result. Arguments are variables defined inside the function, and the received data assign to these variables.

Everything was clear?

Section 1. Chapter 1
We're sorry to hear that something went wrong. What happened?
some-alt