Create and use a global variable in a function in Python

In this tutorial, we will learn about global variables and their usage. Python uses variables to hold data. Variables created outside the function or in the global scope are called global variables. The name global variable tells us that it has scope throughout the program.

Creating a Global Variable

  • To create a global variable, we declare a variable outside the function.

Example:

s="Codespeedy"
def function1():
    print("Hello "+s)
function1()

Output:

Hello Codespeedy

Here, the variable ‘s‘ is created outside of the function named ‘function1’ and used inside the function.

  • We can also create a global variable inside a function using ‘global‘ keyword.

Example:

def function2():
    global s
    s="Codespeedy"
function2()
print(s+" is awesome!!")

Output:

Codespeedy is awesome!!

Using a Global Variable in a Python

  • We can use a global variable inside and outside of the function.

Example:

x="10"
def function3():
    print("Accessing inside function:"+x)
function3()
print("Accessing outside function:"+x)

Output:

Accessing inside function:10
Accessing outside function:10
  • We can also use the same name as the global variable inside a function.

Example:

x="Codespeedy"
def function4():
    x="User"
    print("Hello "+x)
function4()
print("Hello "+x)

Output:

Hello User
Hello Codespeedy
  • We can change the value of a global variable inside a function using the ‘global’ keyword.

Example:

x="User"
def function5():
    global x
    x="Codespeedy"
    print("Hello "+x)
function5()
print("Hello "+x)

Output:

Hello Codespeedy
Hello Codespeedy

Continue reading,

Leave a Reply

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