Python

Understand global variables scope in python

Two types of variables can be defined in most of the programming languages. These are global variables and local variables. The variables which are defined outside the function is called a global variable. This variable is accessible and changeable from anywhere in the script. The variable which is declared inside the function is called the local variable. But if the same variable name exists as global and local variables then the variable inside the function will get the priority and the value of the global variable will be ignored. The scope of the global variable in the python script is shown in this tutorial using various examples.

Example-1: Simple use of a global variable

The following example shows the simple use of a global variable inside the function and outside of the function. Here, a global variable named text is used to assign a string data. A custom function named printMessage() is defined to print the value of the global variable. The value of the text variable is printed inside the function and outside the function after changing the value.

#!/usr/bin/env python3

# Define a global variable
text = "Welcome to LinuxHint"

# Define a function
def printMessage():

  # Print the global variable from the function
  print("Global variable inside function: \n", text)

# Call the function
printMessage()

# Change the value of the global variable
text = "Learn Python Programming"

# Print the current value of the global variable
print("Global variable outside function: \n", text)

Output:

The following output will appear after running the script. It printed the value, ‘Welcome to LinuxHint’ that is assigned to the variable before calling the function. Next, it printed the value, ‘Learn Python Programming’  after changing the value of the variable.

Example-2: Use of global and local variable with the same name

If you want to declare a variable name inside a function that is already declared as a global variable before in python and want to use the variable then it will treat the variable as a local variable and generate an error. The following script will show the error. Here, the text variable is defined as a global and local variable.

#!/usr/bin/env python3

# Define a global variable
text = "I like Python"

# Define a function
def printMessage():
  print(text)

text = "I like PHP"

# Call the function
printMessage()

Output:

The following output will appear after running the script.

To avoid the above situation and if you want to declare a local variable with the same name as a global variable then you have to assign the local variable inside the function first. The following script shows that the changes in the local variable do not make any change in the global variable. text variable is printed inside and outside of the function here.

#!/usr/bin/env python3

# Define a global variable
text = "I like Python"

# Define a function
def printMessage():
  # Degine local value
  text = "I like PHP"
  # Print the local variable,text
  print("The value of 'text' inside function: \n", text)

# Call the function
printMessage()

# Print the global variable, text
print("The value of 'text' outside function: \n", text)

Output:

The following output will appear after running the script.

Example-3: Use of global variable inside the function

The previous example shows that the global variable is not accessible inside a function. You can use the global keyword to access a global variable from any function. In the following script, cal_percentage() function is defined to calculate the percentage of any number where both global and local variables are used. Here, num is a global variable, and perVal is a local variable. global keyword is used here to identify the global variable inside the function and the value of the global variable is changed inside the function.

#!/usr/bin/env python3

# Take an integer value
num = int(input("Enter a number : "))

# Define the function
def cal_percentage():
  # Recognize the global variable using global keyword
  global num

  # Take an integer value as percentage
  perVal = int(input("Enter the percentage value : "))

  # Calculate the percentage value
  result = float((num * perVal)/100)

  # Print the formatted result
  print("%d percentage of %d = %f" %(perVal, num, result))

  # Change the value of global variable
  num = 500

# Print the value of global variable before calling the function
print("\nThe value of num = %d" %num)

# Call the function
cal_percentage()

# Print the value of global variable after calling the function
print("\nThe value of num = %d" %num)

Output:

The following output will appear after running the script. Here, 10% of 350 is calculated and printed.

Example-4: Use of global variables from another script

The following example shows that how the global variable declared in one script can be used in another script. Suppose, the filename is global6.py that will use the global variables defined in the file named global5.py. Three global variables are declared in global5.py. You have to import global5 to use the variables in another script. The script of global6.py will calculate the salary of three types of employees based on input values and global variables.

#!/usr/bin/env python3
# this is global5.py file

# Basic salary structure of a company
Basic = 5000
Medical = 500
Transport = 500
#!/usr/bin/env python3
# this is global6.py file

# Import the global variables from global5.py
import global5

# Take the employee name
name = input("Enter the employee name: ")
# Take the post name
post = input("Enter the post: ")

# Initialize the error variable
error = False

# Check the post and set basic salary based on post
if(post.upper() == "CEO"):
  basic = global5.Basic + (global5.Basic*0.4)
elif(post.upper() == "MANAGER"):
  basic = global5.Basic + (global5.Basic*0.25)
elif(post.upper() == "ACCOUNTANT"):
  basic = global5.Basic + (global5.Basic*0.15)
else:
  # Set error to true if post value not found
  error = True

# Print the salary if error is flase
if (error == False):
  salary = basic + global5.Medical + global5.Transport
  print("The salary of %s is %d" %(name, salary))
else:
  print("Post is not found")

Output:

The following output will appear after running the script. Here, the script is run two times with a valid post and invalid post.

Conclusion:

The concept of a global variable in python is explained in this tutorial with the various simple examples for the new python users. I hope the readers will get the proper knowledge of global variables as well as local variables after reading this tutorial.

About the author

Fahmida Yesmin

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.