Python Scope

Scope refers to the region of a program where a variable is accessible. Python has different types of scope, including local scope, global scope, and built-in scope. Understanding scope helps in avoiding variable conflicts and managing variable visibility.

Local Scope

Variables defined inside a function have a local scope, meaning they are only accessible within that function.

In this example, x is a local variable and can only be accessed inside my_function.

Tutorials dojo strip
Python

Global Scope

Variables defined outside any function have a global scope, meaning they are accessible throughout the entire program.

In this example, x is a global variable and can be accessed both inside and outside my_function.

Python

Modifying Global Variables

To modify a global variable inside a function, you need to use the global keyword.

The global keyword allows you to reference the global variable inside the function. In this example, the global keyword is used to modify the global variable x inside my_function.

Python

Enclosing Scope

Enclosing scope refers to variables defined in a function that is within another function. These variables are accessible to the inner function.

This is also known as the non-local scope. In this example, y is an enclosing variable and can be accessed by inner_function.

Python

Built-in Scope

Built-in scope refers to names preassigned by Python. These names are always available, regardless of the scope.

The len function is an example of a built-in function available in the built-in scope.

Python

Python Labs

Tutorials dojo strip