You can use a global variable within other functions by declaring it as global within each function that assigns a value to it:

globvar = 0

def set_globvar_to_one():
    global globvar    # Needed to modify global copy of globvar
    globvar = 1

def print_globvar():
    print(globvar)     # No need for global declaration to read value of globvar

set_globvar_to_one()
print_globvar()       # Prints 1

Since it's unclear whether globvar = 1 is creating a local variable or changing a global variable, Python defaults to creating a local variable, and makes you explicitly choose the other behavior with the global keyword.

See other answers if you want to share a global variable across modules.

Answer from Paul Stephenson on Stack Overflow
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_variables_global.asp
Python - Global Variables
Global variables can be used by everyone, both inside of functions and outside. Create a variable outside of a function, and use it inside the function ยท x = "awesome" def myfunc(): print("Python is " + x) myfunc() Try it Yourself ยป
Top answer
1 of 16
5288

You can use a global variable within other functions by declaring it as global within each function that assigns a value to it:

globvar = 0

def set_globvar_to_one():
    global globvar    # Needed to modify global copy of globvar
    globvar = 1

def print_globvar():
    print(globvar)     # No need for global declaration to read value of globvar

set_globvar_to_one()
print_globvar()       # Prints 1

Since it's unclear whether globvar = 1 is creating a local variable or changing a global variable, Python defaults to creating a local variable, and makes you explicitly choose the other behavior with the global keyword.

See other answers if you want to share a global variable across modules.

2 of 16
932

If I'm understanding your situation correctly, what you're seeing is the result of how Python handles local (function) and global (module) namespaces.

Say you've got a module like this:

# sample.py
_my_global = 5

def func1():
    _my_global = 42

def func2():
    print _my_global

func1()
func2()

You might be expecting this to print 42, but instead, it prints 5. As has already been mentioned, if you add a 'global' declaration to func1(), then func2() will print 42.

def func1():
    global _my_global 
    _my_global = 42

What's going on here is that Python assumes that any name that is assigned to, anywhere within a function, is local to that function unless explicitly told otherwise. If it is only reading from a name, and the name doesn't exist locally, it will try to look up the name in any containing scopes (e.g. the module's global scope).

When you assign 42 to the name _my_global, therefore, Python creates a local variable that shadows the global variable of the same name. That local goes out of scope and is garbage-collected when func1() returns; meanwhile, func2() can never see anything other than the (unmodified) global name. Note that this namespace decision happens at compile time, not at runtime -- if you were to read the value of _my_global inside func1() before you assign to it, you'd get an UnboundLocalError, because Python has already decided that it must be a local variable but it has not had any value associated with it yet. But by using the 'global' statement, you tell Python that it should look elsewhere for the name instead of assigning to it locally.

(I believe that this behavior originated largely through optimization of local namespaces -- without this behavior, Python's VM would need to perform at least three name lookups each time a new name is assigned to inside a function (to ensure that the name didn't already exist at module/builtin level), which would significantly slow down a very common operation.)

Discussions

How to make variables global by default, Python 3.11
I have Python 3.11 on Windows 10 Pro. Iโ€™m still a bit new to Python but Iโ€™m learning. In Python 3.11 the variables declared in the main program are not global by default and I cannot use them in functions. So if I want to use them in a function I have to use the global prefix/keyword. More on discuss.python.org
๐ŸŒ discuss.python.org
0
0
June 10, 2024
How to declare a global variable in Python correctly - Stack Overflow
I have the following piece of code that presented below with tic-tac-toe implementation. As far as I understand variable "player" is global one and it's value 'X' should be accessed from ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to handle 'global' variables?
Hi, Newby question here. Iโ€™m creating a program that traverses a directory tree using os.walk. Each directory in that tree is checked for a distinct text file, the text file is opened, and the contents searched for image filenames & urls. I want to keep track of the total number of text files ... More on discuss.python.org
๐ŸŒ discuss.python.org
0
0
May 8, 2024
Is there a way to make a variable global to all functions?
Sounds like you maybe want a class instead. All functions would be implemented as methods on the class that can all access the class instance's variables. More on reddit.com
๐ŸŒ r/learnpython
18
0
April 22, 2025
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ when declaring a global variable, do you "need" to make a function using it?
r/learnpython on Reddit: When declaring a global variable, do you "need" to make a function using it?
August 5, 2024 -

Recently, my teacher and I had some problems about this particular lesson that could not be solve because of both of us being stubborn. Note that this is a beginner class for programmers and the teacher was using a website w3schools to teach in his lesson. When he was revising the lesson in Python Variables, he asked "Create a global variable". Many students rose their hand then he decided to choose me. I went up to the board and wrote var1 = "hello, world!". You might say this is a very simple and easy line of code. I was sure this couldn't be wrong since I knew the definition global variable and that is variables that are created outside of a function (as in all of the examples in the previous pages in w3schools) are known as global variables. This definition tought me that I didn't need to make a function (like local variables) to make a global variable. Then afterwards he decided to mock me saying after I was wrong. Different from everyone else. I was wrong that my code needed more line. Specificly a function and an output to consider it as a global variable. This situation escalated to threatening me to the principle and calling about another teacher to prove me wrong. Ofcourse I did respond to this matter back respectfully but he couldn't agree with me. I was trying act like I was not mad to be respectful and not use any informal behaviour. Though I am starting to be annoyed of this. After all, he did told be to do my research to find "a professor" to proof me wrong, etc. I decided to ask reddit if I am truly in the wrong or not and to see any other opinions of my fellow reddit users about this matter. And if I am right, this reddit might be use to prove the teacher to getting my "deserving points" back from a complex misunderstanding.

Edit: var1 = "hello, world!" is written completely by itself and not inside of anything. And the teacher specificly said "Create a global variable" so that mean no function was mention. I hope this could give out some more ideas about the perspective. And as mention the class have only learnt to python variables so as of reading the comments, I couldn't even understand what some of the lines of code you guys wrote.

Top answer
1 of 11
28
Your teacher needs to specify their question better, this is exactly how you declare a global variable. A better question might have been show how to use a declare global variable in a function. Source: Software developer (as my job) since 2000, switched to Python in 2008. EDIT: I re-read and notice your teacher is using w3schools to teach the lessons from, that's pretty shocking. People are pretty snobby about it, but I'd say it's OK for a quick reference but that's about all - it is absolutely not a good enough reference to be building a curriculum around. In the short term, just keep the guy somewhat happy, his attitude doesn't seem the most professional, just by using proper references (start with the actual python documentation, If you ever find yourself having to teach a python class in the future, then I would recommend actual books as reference; e.g. the O'Reilly book - Learning Python. At the point when I started developing everything was book based, and we had shelves of books in offices we worked in too, there were always O'Reilly books there (if you can, I'd recommend getting a book like that yourself).
2 of 11
9
I think this is more of a weird interaction than a question about global variables. Teachers should not be "mocking" their students for getting a question wrong, regardless of whether the teacher is correct. But I'm only hearing your side of the story, so I won't make a judgement on that. That being said, this sounds like a problem that is not going to be solved by showing your teacher a reddit thread. So, with that out of the way, I'm going to disappoint you. The correct answer is...you're both right, but your teacher is more right. You are also somewhat both wrong, but I'll touch on that in a minute. There is nothing "special" about the scope of a module; it works just like a function scope. For example: def func1(): global_var = "hello" def func2(): print(global_var) func2() func1() # print(global_var) # Not defined error if uncommented # Output # hello Is global_var global? No, if you tried to print it outside func1 the code fails. All you've done is define a variable in a more "outer" scope compared to other functions. Still, for practical purposes, this is similar to a global variable. But it isn't actually global. For example: var1 = "hello, world!" def my_func(): var1 = "bye!" my_func() print(var1) # Output # hello, world! As you can see, your function doesn't actually modify the variable. Instead, a new local variable is created, assigned a value, and then promptly ignored. So this variable isn't "global" in the normal sense of the word. Instead, you would need to tell Python that you want to use the outer variable: var1 = "hello, world!" def my_func(): global var1 var1 = "bye!" my_func() print(var1) # Output # bye! The reality is that Python does not have "true" global variables. Any time a function needs to actually modify an outer variable, it must be declared as global within that scope. Read-only access is fine (which is why the print commands worked in the first example) because there is no confusion about whether or not you want to read an existing variable or create a new one. But any time you assign a value to a "global" variable you must tell the interpreter that this is your intent. Languages with "true" global variables don't require this because you define it as accessible everywhere at definition. In summary: You are correct that a variable defined at an outer scope can be read at an inner scope, similar to global variables. Your teacher is correct that without a global keyword definition, the variable is not actually global in the Pythonic sense. You are both wrong because true "global variables" are not a concept in Python. Using global variables is an antipattern anyway and you are both being immature for making it into a fight. In my opinion, number 4 is the most important. You hardly ever use the global keyword in actual programs and using variables in lower scopes is a "code smell". Don't be lazy...pass your parameters, and if you don't want to do that because the parameter is used a lot, create a class. You will almost never see this keyword in production code and having this go to the principle about something that is almost completely irrelevant to learning programming is bad behavior on both your parts, at least in my opinion. That probably isn't the answer you wanted. But it's the truth.
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
How to make variables global by default, Python 3.11 - Python Help - Discussions on Python.org
June 10, 2024 - In Python 3.11 the variables declared in the main program are not global by default and I cannot use them in functions. So if I want to use them in a function I have to use the global prefix/keyword.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ global-local-variables-python
Global and Local Variables in Python - GeeksforGeeks
Global variables are declared outside all functions and can be accessed anywhere in the program, including inside functions. In this example, we are creating a global variable and then accessing it both inside and outside a function. ... msg = "Python is awesome!" def display(): print("Inside function:", msg) display() print("Outside function:", msg)
Published ย  September 20, 2025
Find elsewhere
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
How to handle 'global' variables? - Python Help - Discussions on Python.org
May 8, 2024 - Hi, Newby question here. Iโ€™m creating a program that traverses a directory tree using os.walk. Each directory in that tree is checked for a distinct text file, the text file is opened, and the contents searched for image filenames & urls. I want to keep track of the total number of text files ...
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ assigning-global-variables
Assigning to global variables - Python Morsels
January 28, 2021 - Assigning to message while at the module-level (outside of any function), changes the global message variable directly: ... If we wanted to change it to something else, we'd pass in a different argument, and continue to assign to the message variable: >>> message = get_message("Guido") >>> message 'Hello Guido' Typically in Python we embrace the fact that all assignments are local; unless you're in the global scope (you're outside of any function) because then assignment statements will assign to the global scope.
๐ŸŒ
Real Python
realpython.com โ€บ python-use-global-variable-in-function
Using and Creating Global Variables in Your Python Functions โ€“ Real Python
December 8, 2024 - However, if you want to modify a global variable within a function, you need to use the global keyword to declare that youโ€™re working with the global variable and not creating a new local variable.
๐ŸŒ
Simplilearn
simplilearn.com โ€บ home โ€บ resources โ€บ software development โ€บ python global variables | definition, scope and examples
Python Global Variables | Definition, Scope and Examples
September 9, 2025 - Python global variables explained! Learn how to declare, modify and use them effectively while understanding their scope, limitations and best practices.
Address ย  5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Global variables shared across modules - Python Help - Discussions on Python.org
June 25, 2022 - Hello to all Pythonians here. I encountered a strange behavior about the global keyword and modules, which I cannot understand. Module test1: Variable a is created Module test2: Module test1 is imported, and function f is created, which modifies variable a through the global keyword Module test3: Modules test1 and test2 are imported, f is called, and a is printed.
๐ŸŒ
Great Learning
mygreatlearning.com โ€บ blog โ€บ it/software development โ€บ global variables in python
Global Variables in Python
August 15, 2024 - To declare a global variable in Python, you need to use the global keyword followed by the variable name.
๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ python โ€บ use global variables in python functions
Use global variables in Python functions | Sentry
March 15, 2023 - def create_counter(): global counter counter = 1 def increment_counter(): global counter counter += 1 def print_counter(): global counter print(counter) create_counter() print_counter() increment_counter() print_counter() increment_counter() ...
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ global-variable-in-python-non-local-python-variables
Global Variable in Python โ€“ Non-Local Python Variables
June 10, 2022 - In Python and most programming languages, variables declared outside a function are known as global variables. You can access such variables inside and outside of a function, as they have global scope.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ faq โ€บ programming.html
Programming FAQ โ€” Python 3.14.3 documentation
Since the last statement in foo assigns a new value to x, the compiler recognizes it as a local variable. Consequently when the earlier print(x) attempts to print the uninitialized local variable and an error results. In the example above you can access the outer scope variable by declaring it global:
๐ŸŒ
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!
If you always only use in a function what was explicitly given to the function, it becomes easier to find a mistake because you know exactly where to check: At the door (parameter list). ... 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
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ python-global-variables-examples
Python Global Variables โ€“ How to Define a Global Variable Example
May 12, 2022 - #global variable city = "Athens" ... of global variable print(f"I want to visit {city} next year!") Use the global keyword before referencing it in the function, as you will get the following error: SyntaxError: name 'city' is ...
๐ŸŒ
Index.dev
index.dev โ€บ blog โ€บ how-to-set-global-variables-python
How to Set Global Variables Across Modules in Python
Setting global variables across modules in Python can be done in multiple ways, from simple imports to using the singleton pattern. The best approach depends on your use case. If you need a quick solution, using a separate config module works well.
๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ python โ€บ built-in โ€บ globals
Python globals() - Access Global Variables | Vultr Docs
September 27, 2024 - You will explore practical examples ... manage state across different parts of your Python application. Define global variables in the main body of your script....