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.

Tutorials dojo strip

Explanation of Code:

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




Global Scope

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

Explanation of Code:

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




Modifying Global Variables

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

Explanation of Code:

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.




Enclosing Scope

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

Explanation of Code:

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




Built-in Scope

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

Explanation of Code:

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




Python Labs

Tutorials dojo strip