Python Variables and Scope

Understanding variables and scope is fundamental to writing efficient and error-free Python code.

Python Variables

A variable is a name that refers to a value stored in memory.

x = 10
name = "Simran"

Variable Types by Scope

In Python, variables have scope, which determines where they can be accessed or modified.

1. Local Variables

  • Defined inside a function.
  • Accessible only within that function.
def my_function():
   message = "Hello"
   print(message)
my_function()

Output:

Hello

Trying to access message outside the function will result in an error.

2. Global Variables

  • Defined outside of all functions.
  • Can be accessed inside functions, but not modified unless declared with global.
name = "Simran"
def greet():
   print("Hello", name)
greet()

Output:

Hello Simran

3. Modifying Global Variables inside a Function

count = 0
def increment():
   global count
   count += 1
increment()
print(count)

Output:

1

Explanation:

  • global count allows the function to change the global variable count.

4. Enclosing (Nonlocal) Scope – Nested Functions

def outer():
   msg = "Hello"
   def inner():
       nonlocal msg
       msg = "Hi"
       print("Inner:", msg)
   inner()
   print("Outer:", msg)
outer()

Output:

Inner: Hi
Outer: Hi

Explanation:

  • nonlocal msg modifies the msg variable from the enclosing (outer) function.

Summary Table

TypeDefined InAccess ScopeKeyword Used
LocalFunctionInside same function(None)
GlobalScript levelEverywhereglobal
NonlocalOuter functionInner functionsnonlocal