Skip to content

Global Variables

We can create a variable outside of a function. This is called a global variable. We can access the global variable inside or outside of a function. Let’s see an example.

Example:

variable.py
# Global variable
name = "John"
def display():
    print("Hello, " + name)
display()
print("Hello, " + name)
variable.py
# Global variable
name = "John"
def display():
    print("Hello, " + name)
display()
print("Hello, " + name)

Output:

command
C:\Users\Your Name> python variable.py
Hello, John
Hello, John
command
C:\Users\Your Name> python variable.py
Hello, John
Hello, John

In the above example, we created a global variable namename outside of the function display()display(). We can access the global variable namename inside or outside of the function display()display().

Global Keyword

We can create a local variable inside a function. This is called a local variable. We can access the local variable inside the function. We can’t access the local variable outside the function. Let’s see an example.

Example:

variable.py
# Global variable
name = "John"
def display():
    # Local variable
    name = "Smith"
    print("Hello, " + name)
display()
print("Hello, " + name)
variable.py
# Global variable
name = "John"
def display():
    # Local variable
    name = "Smith"
    print("Hello, " + name)
display()
print("Hello, " + name)

Output:

command
C:\Users\Your Name> python variable.py
Hello, Smith
Hello, John
command
C:\Users\Your Name> python variable.py
Hello, Smith
Hello, John

In this example, we created a local variable namename inside the function display()display(). We can access the local variable namename inside the function display()display(). We can’t access the local variable namename outside the function display()display().

We can use the globalglobal keyword to access the global variable inside the function. Let’s see an example.

Example:

variable.py
# Global variable
name = "John"
def display():
    # Local variable
    global name
    name = "Smith"
    print("Hello, " + name)
display() 
print("Hello, " + name) 
variable.py
# Global variable
name = "John"
def display():
    # Local variable
    global name
    name = "Smith"
    print("Hello, " + name)
display() 
print("Hello, " + name) 

Output:

command
C:\Users\Your Name> python variable.py
Hello, Smith
Hello, Smith
command
C:\Users\Your Name> python variable.py
Hello, Smith
Hello, Smith

In this example, we used the globalglobal keyword to access the global variable namename inside the function display()display(). We can access the global variable namename inside the function display()display(). We can also access the global variable namename outside the function display()display().

Was this page helpful?

Let us know how we did