Python Global and Local variables

  • Python

In this tutorial, we’ll learn about global variables, local variables in python. We’ll also learn where to use them and how to use them.

Global Variables

Variables when defined outside the function in the global namespace, are known as global variables. This variable can be accessed both from inside and outside the function.

Let’s understand this using an example.

x = "Techie"

def func():
  print(x + " Inside")

func()
print(x + " Outside")

Output :

Techie Inside
Techie Outside

In the above example, we defined a variable x outside the function and accessed the same inside the function as well.

Local Variables

Variables defined inside the function are known as local variables. A local variable cannot be accessed from outside of the function.

Let’s understand using an example.

x = "Hours"

def func():
  x = "Techie"
  print(x + " Inside")

func()
print(x + " Outside")

Output :

Techie Inside
Hours Outside

In the above example, we defined the same variable twice. Once outside the function and second outside the function. The function func() did not use the global variable as the preference if given to the local variable.

Now , if you want to change the value of global variable inside the function we need to explicitly mention the variable as global.

x = "Hours"

def func():
  global x
  x = "Techie"
  print(x + " Inside")

func()
print(x + " Outside")

Output :

Techie Inside
Techie Outside

In this example, we changed x to a global variable and changed it’s value to Techie which changed the value of global variable.