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

Зміст курсу

Mastering Python: Closures and Decorators

Mastering Python: Closures and Decorators

1. Scopes
2. Closure
3. Decorators

What are scopes?

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

Let's consider the example:

12345678910
number = 15 print("Regular: number =", number) def some_function(): number = 256 print("Function: number =", number) some_function() print("Regular: number =", number)
copy

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.:

1234567891011
number = 2077 string = "Global scope" print(len(string)) def add(first, second): result = first + second return result print(add(25, 13)) print(result) # NameError: no `result` variable in the global scope.
copy

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.

Все було зрозуміло?

Секція 1. Розділ 1
We're sorry to hear that something went wrong. What happened?
some-alt