Global variable declaration inside function (Python

If you only want to read (access) the value of a global variable, you do not need the global keyword. Python automatically looks up the variable in the global scope if it doesn’t find it locally.

However, the global keyword is mandatory if you want to modify (write to) that variable.

Here is the breakdown of why it exists.

1. Reading (No global needed)

As you noticed, this works fine. Python looks for count locally, fails, looks globally, and finds it. code Pythondownloadcontent_copyexpand_less

    count = 10

def read_variable():
    # Works perfectly without 'global'
    print(count) 

read_variable() # Output: 10
  

2. Writing WITHOUT global (The Trap)

If you try to assign a value to a variable inside a function, Python assumes you are creating a new local variable with the same name. It does not touch the global variable. This is called “shadowing.” code Pythondownloadcontent_copyexpand_less

    count = 10

def try_to_change():
    count = 99  # Python creates a NEW local variable named 'count'
    print(f"Inside: {count}")

try_to_change()   # Output: Inside: 99
print(f"Outside: {count}") # Output: Outside: 10 (The global one didn't change!)
  

3. Writing WITH global (The Fix)

If you want to change the variable that lives outside the function, you must explicitly tell Python, “I am referring to the global variable, not making a new one.” code Pythondownloadcontent_copyexpand_less

    count = 10

def actually_change():
    global count  # Tell Python to use the outside variable
    count = 99    # Now this updates the global variable
    print(f"Inside: {count}")

actually_change() # Output: Inside: 99
print(f"Outside: {count}") # Output: Outside: 99 (It changed!)
  

4. The Crash (UnboundLocalError)

This is the most common error people encounter. If you try to read and write the variable in the same function without global, Python gets confused.

Because there is an assignment (count += 1) anywhere in the function, Python decides count is local. But since you try to read it before assigning it, it crashes. code Pythondownloadcontent_copyexpand_less

    count = 10

def increment():
    # ERROR! UnboundLocalError: local variable 'count' referenced before assignment
    count = count + 1 

increment()
  

The Fix: code Pythondownloadcontent_copyexpand_less

    def increment():
    global count
    count = count + 1 # Now it works
  

Summary

  • Reading only: global is not required.
  • Assigning/Updating: global is required.

Leave a Reply

Your email address will not be published. Required fields are marked *