Global Variables in Python

This tutorial will explain the global variables and how to declare and use the global variables in Python.

The global variables are the variables with global scope. The global scope means the variable is accessible from anywhere in the program. The global variables are declared outside the functions as their scope is not limited to any function. The lifetime of the global variable is equal to the runtime of the program.

We can declare and access the global variables in Python using the method explained below:

Declare and Use Global Variable in Python Using the global Keyword

We do not have to explicitly declare the variables before using them, therefore to differentiate between a local and global variable, we need to specify that the variable we are accessing is the global variable or not. We can specify a variable as global in Python by using the global keyword.

If we pass the value to the global variable within a function without declaring it as a global variable, the value will be passed to the new variable with the same name. And the scope of the new variable will be restricted to the scope of the function.

Suppose we have a global variable date, and we want to update the value of the date using the function update_date() without using any arguments. The below example code demonstrates how to access the global variable from a function.

date = "17-06-2002"

def update_date():
  global date 
  date = "12-03-2021"

update_date()
print(date)

Output:

12-03-2021

Now let’s check the value of the global variable date if we do not specify it as a global variable using the global keyword:

date = "17-06-2002"

def update_date():
  date = "12-03-2021"

update_date()
print(date)

Output:

17-06-2002
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python Variable

  • Check Variable Type in Python