Scope of a Variable

In Python, scope refers to the region of a program where a particular variable or name is accessible and can be used.

Global Scope

Variables defined at the top level of a Python script or module have global scope. They can be accessed from anywhere in the script or module, including within functions and classes.

Local Scope

Variables defined within a function, method, or a code block (such as a loop or conditional statement) have local scope. They are only accessible within the block where they are defined.

Note: Local variables are temporary and exist only for the duration of the block in which they are defined.

Nested Scope

Python allows for nested scopes, where you have access to variables from outer (enclosing) scopes within inner scopes, but not vice versa. If a variable is not found in the local scope, Python will look in the nearest enclosing scopes, including the global scope, until it finds the variable or reaches the built-in scope.

LEGB Rule

Python follows the LEGB rule to determine the order in which it looks for a variable name:

  • Local (L): The innermost scope, which is the current function or code block.
  • Enclosing (E): The scope of any enclosing functions, going outwards.
  • Global (G): The global scope, which includes variables defined at the module level.
  • Built-in (B): The built-in scope, which contains Python's built-in functions and objects.

Python searches for a variable name in this order until it finds a match.

The global Keyword

In Python, the global keyword is used to indicate that a variable declared inside a function should have a global scope rather than a local scope. This means that the variable can be accessed and modified from anywhere in the code, including both inside and outside the function where it was originally defined.

Local and Global Variables with the same name

If local and global variables have same name, then they are different variables. A local variable is created when the function or code block is entered and is destroyed (or goes out of scope) when the function or code block exits.

Practice Exercises

Complete these exercises to reinforce your learning and earn XP

Sign in to track your progress and earn XP!
Exercise 1 of 2Easy

Which of the following is a valid variable name?

10 XP~3 min
Exercise 2 of 2Easy

To declare an integer variable named 'age', we write: ___ age;

10 XP~2 min