Python Global Variables
Learn about global variables in Python, which are defined outside of functions and can be accessed globally. Discover how to use and manipulate these variables within functions and across your Python code.
Python - Global Variables
Global variables are variables that are created outside of a function. These variables can be accessed both inside and outside of functions.
Using Global Variables Inside Functions
Here's an example of creating a variable outside a function and using it inside the function:
Example
x = "awesome"
def myfunc():
print("Coding is " + x)
myfunc()
Output
Coding is awesome
Local vs Global Variables with the Same Name
If you create a variable with the same name inside a function, it will be local to that function. The global variable with the same name will remain unchanged.
Example
x = "awesome"
def myfunc():
x = "fantastic"
print("Coding is " + x)
myfunc()
print("Coding is " + x)
Output
Coding is fantastic
Coding is awesome
The global
Keyword
Normally, when you create a variable inside a function, it is local to
that function. To create a global variable inside a function, use the
global
keyword.
Example
def myfunc():
global x
x = "fantastic"
myfunc()
print("Coding is " + x)
Output
Coding is fantastic
You can also use the global
keyword to modify a global
variable inside a function.
Example
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Coding is " + x)
Output
Coding is fantastic