Global variables are special. If you try to assign to a variable a = value inside of a function, it creates a new local variable inside the function, even if there is a global variable with the same name. To instead access the global variable, add a global statement inside the function:

a = 7
def setA(value):
    global a   # declare a to be a global
    a = value  # this sets the global value of a

See also Naming and binding for a detailed explanation of Python's naming and binding rules.

Answer from Adam Rosenfield on Stack Overflow
Top answer
1 of 6
190

Global variables are special. If you try to assign to a variable a = value inside of a function, it creates a new local variable inside the function, even if there is a global variable with the same name. To instead access the global variable, add a global statement inside the function:

a = 7
def setA(value):
    global a   # declare a to be a global
    a = value  # this sets the global value of a

See also Naming and binding for a detailed explanation of Python's naming and binding rules.

2 of 6
16

The trick to understanding this is that when you assign to a variable, using =, you also declare it as a local variable. So instead of changing the value of the global variable a, setA(value) actually sets a local variable (which happens to be called a) to the value passed in.

This becomes more obvious if you try to print the value of a at the start of setA(value) like so:

def setA(value):
    print "Before assignment, a is %d" % (a)
    a = value
    print "Inside setA, a is now %d" % (a)

If you try to run this Python will give you a helpful error:

Traceback (most recent call last):
  File "scopeTest.py", line 14, in 
    setA(42)
  File "scopeTest.py", line 7, in setA
    print "Before assignment, a is %d" % (a)
UnboundLocalError: local variable 'a' referenced before assignment

This tells us that Python has decided that the setA(value) function has a local variable called a, which is what you alter when you assign to it in the function. If you don't assign to a in the function (as with printA()) then Python uses the global variable A.

To mark a variable as global you need to use the global keyword in Python, in the scope that you want to use the global variable. In this case that is within the setA(value) function. So the script becomes:

a = 7

def printA():
    print "Value of a is %d" % (a)

def setA(value):
    global a
    a = value
    print "Inside setA, a is now %d" %(a)


print "Before setA"
printA()
setA(42)
print "After setA"
printA()

This one line addition tells Python that when you use the variable a in the setA(value) function that you are talking about the global variable, not a local variable.

🌐
Python
docs.python.org › 3 › faq › programming.html
Programming FAQ — Python 3.14.4 documentation
This happens because x is not local to the lambdas, but is defined in the outer scope, and it is accessed when the lambda is called — not when it is defined. At the end of the loop, the value of x is 4, so all the functions now return 4**2, that is 16. You can also verify this by changing the value of x and see how the results of the lambdas change: ... In order to avoid this, you need to save the values in variables local to the lambdas, so that they don’t rely on the value of the global x:
Discussions

Why can't I set a global variable in Python? - Stack Overflow
How do global variables work in Python? I know global variables are evil, I'm just experimenting. This does not work in python: G = None def foo(): if G is None: G = 1 foo() I get an More on stackoverflow.com
🌐 stackoverflow.com
Global variable is not recognised in a function
If you assign to a global variable inside a function, you need to explicitly state it to be global by adding global var_name at the top of your function declaration. x = 5 def modify_global(): global x x = 3 More on reddit.com
🌐 r/learnpython
6
2
March 3, 2022
Why the global variable is not working in the different functions in Python? - Stack Overflow
Note: If possible, move global variables and related functions into a class. ... Sign up to request clarification or add additional context in comments. ... def appnd(): j=i while i in range(i,j+3): print "%s .Line..\n" %i # it would print infinitely, but will work · At compile time Python looks ... More on stackoverflow.com
🌐 stackoverflow.com
April 17, 2012
Global variables not working in functions
I am confused why only the health variable works and not the others. Is it because the others aren’t numbers? And if this the case, why does yes not work? Does it have something to do with the fact that yes isn’t a positive number? global health = 50 global maxhealth = 100 global minhealth ... More on discuss.python.org
🌐 discuss.python.org
1
0
July 23, 2025
🌐
Python.org
discuss.python.org › python help
Can't use global variables within a function - Python Help - Discussions on Python.org
November 19, 2021 - Today i’m trying out functions, but i’ve run in a small (inconsistancy?) issue. Mainly i’m trying to print out global variables within a function, which works, but when I try to change the value of the pre-created variables, from inside the function, its not allowing me.
🌐
W3Schools
w3schools.com › python › python_variables_global.asp
Python - Global Variables
If you use the global keyword, the variable belongs to the global scope: def myfunc(): global x x = "fantastic" myfunc() print("Python is " + x) Try it Yourself »
🌐
Quora
quora.com › Why-is-a-global-variable-not-changed-in-Python
Why is a global variable not changed in Python? - Quora
You might think that line 3 should overwrite the global variable in line 1, but Python simply doesn’t work like that. Unless you tell Python otherwise the ‘a’ defined on line 3 is a local variable which is only used in the ‘func’ function. Python ignores the name overlap. If you really want to use global values (not really a good idea - but there you go), you have to tell Python that ‘a’ inside ‘func’ is a global - and not a local.
🌐
Reddit
reddit.com › r/learnpython › global variable is not recognised in a function
r/learnpython on Reddit: Global variable is not recognised in a function
March 3, 2022 -

Hi,

I have the following situation. I am building hangman game, so far it works well, I can get a random number from the list and start guessing letters. I have 7 tries because I have 7 stages of hanging in the stages list. For some reason I cannot get my counter to work, in order to count the amount of times I have the wrong letter and print the correct image (actually it prints the correct image, but even if my letter is right the counter adds one).

In the code I have marked the two places that I have problem with (<-------- This variable ------------). I have declared a global variable and in one of my functions I add 1 to it if the statement is True. For some reason this variable is not recognised as global. Any suggestions on how to overcome this problem?

I have some commented code in my last function, that also doesn't work as expected. If letter_guesses is used in the last function from the code it works but in the place_letter function it is not recognised.

import random

word_list = ["aardvark", "baboon", "camel"]

# Task 1 select a word from list
chosen_word = random.choice(word_list)
print(chosen_word)

hidden_word = []

for letter in chosen_word:
    hidden_word.append("_")

stages = ['''
  +---+
  |   |
  O   |
 /|\  |
 / \  |
      |
=========
''', '''
  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========
''', '''
  +---+
  |   |
  O   |
 /|\  |
      |
      |
=========
''', '''
  +---+
  |   |
  O   |
 /|   |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
  |   |
      |
      |
=========
''', '''
  +---+
  |   |
  O   |
      |
      |
      |
=========
''', '''
  +---+
  |   |
      |
      |
      |
      |
=========
''']


def split_word(word):
    return [char for char in word]


letter_guesses = 0 #<-------- This variable ------------


def place_letter():
    letter_input = input("Guess a letter: ").lower()
    checker = split_word(chosen_word)
    for index, letter in enumerate(chosen_word):
        if letter == letter_input:
            hidden_word.pop(index)
            hidden_word.insert(index, letter_input)
        else:
            pass
    if letter_input not in checker:
        letter_guesses += 1 #<-------- This variable ------------
        print(stages[(len(stages) - 1) - letter_guesses])


while "_" in hidden_word or letter_guesses <= 7:
    place_letter()
    print(hidden_word)
    # if letter_input not in split_word(chosen_word):
    #     letter_guesses += 1
    if "_" not in hidden_word:
        print("You won!")
        break
    if letter_guesses >= len(stages):
        print("You lost.")
        break
Find elsewhere
🌐
Real Python
realpython.com › python-use-global-variable-in-function
Using and Creating Global Variables in Your Python Functions – Real Python
December 8, 2024 - Note that you can define this variable in any of the three scopes, and Python will find it. This search mechanism makes it possible to use global variables from inside functions. However, while taking advantage of this feature, you can face a few issues. For example, accessing a variable works, but directly modifying a variable doesn’t work:
🌐
JetBrains
youtrack.jetbrains.com › issue › PY-47759
global variables are not working, when global is used i'm ...
{{ (>_<) }} This version of your browser is not supported. Try upgrading to the latest stable version. Something went seriously wrong
🌐
Programiz
programiz.com › python-programming › global-local-nonlocal-variables
Python Variable Scope (With Examples)
To fix this issue, we can make the variable named message global. In Python, a variable declared outside of the function or in global scope is known as a global variable.
🌐
Python Forum
python-forum.io › thread-32018.html
Global variables not working
I have made some global variables. A simplified version of the program (but with the same rationale) is this: sentence_1 = "hello" sentence_2 = "hello" class MyClass: def __init__(self, parent = None)
🌐
Blender Artists
blenderartists.org › coding › python support
Global variable in py-driver not working as expected - Python Support - Blender Artists Community
December 27, 2023 - Hi all! So first off, I’ll admit I’m a hack at python. I’m playing with a python driver and I want to store a value outside of the function that is called when the driver is evaluated. Here’s my code: import bpy max_value = 0.0 print("max_value = ", max_value) def check_max(input): print(max_value) if input > max_value: max_value = input return max_value bpy.app.driver_namespace["check_max"] = check_max I assign a value to max_value outside of the chec...
🌐
Net Informations
net-informations.com › python › iq › global.htm
Global and Local Variables in Python
Within the my_function function, you declare a local variable named x with a value of 5. When the my_function function is called, it prints the value of the local variable x, which is 5. When you print the value of the global variable x outside of the function, it is still 10. The global keyword in Python is used to indicate that a variable is a global variable, rather than a local variable.
🌐
Quora
quora.com › Why-is-the-global-variable-not-updating-inside-a-function
Why is the global variable not updating inside a function? - Quora
Symptom: changes via methods visible outside; assignment not visible. Fix: mutate in place, or explicitly assign to the global name. ... Rebind requires global: items = [] # inside function needs global declaration to affect module-level name · Using a different scope (nested functions, closures) Problem: nested function assigns to a variable from outer function; Python treats it as local unless declared nonlocal.
🌐
freeCodeCamp
freecodecamp.org › news › global-variable-in-python-non-local-python-variables
Global Variable in Python – Non-Local Python Variables
June 10, 2022 - Using the global keyword in the code above, we were able to modify x and add 2 to its initial value. When we created a variable inside a function, it wasn't possible to use its value inside another function because the compiler did not recognize the variable.
🌐
Sololearn
sololearn.com › en › Discuss › 1806072 › how-do-i-create-global-variables-in-python-without-the-gloabal-keyword
How do I create global variables in python without the "gloabal" keyword? | Sololearn: Learn to code for FREE!
Nope, it can be used, but not modified (unless it is a list etc. and methods like .append are used. But it can't be changed in place). As soon as a variable is modified in a function and there's no "global" keyword in the function, Python assumes that it is a local variable