How to define global variables in Python?

Understanding global and local variables in Python will allow you to better understand how your code works and what variables are available to you at different points in your code. You need to be aware of which scope a variable is in so that you can access the correct value. It can be easy to get caught up in coding without thinking about which value you’re using and why. By taking the time to think about scope, you can avoid errors and save yourself time later on.

In this article, we will take a look at what global variables are in Python, how to define them, and some of the benefits and drawbacks of using them. We’ll also go over some examples so that you can see how they work.

What is a Global Variable?

A global variable is a variable that is defined outside of a function. It can be accessed by any function in your code. A global variable is declared by using the keyword “global” followed by the name of the variable. The value of the variable can then be assigned.

It’s important to note that if you declare a global variable inside of a function, it will only be accessible within that function. You need to declare it outside of any functions in order for it to be truly global.

Here’s an example:

name = "John" # this is a global variable def sayHello(): print("Hello " + name) # this will print "Hello John" sayHello() # calling the function will print "Hello John" def changeName(): global name # we need to use the "global" keyword here name = "Jane" # now we can change the value of the name variable changeName() # calling the function will now print "Hello Jane" because we changed the value of the name variable inside of this function sayHello() # calling our original function now prints "Hello Jane" because we changed the value of our global variable inside of another function
Code language: Python (python)

As you can see from this example, all functions have access to global variables once they are defined. However, if you want to change the value of a global variable from within a function, you need to use the “global” keyword so that Python knows that you want to edit the existing global variable and not create a new local one.

If you try to access or change a global variable without using the “global” keyword from within a function, Python will either return an error or create a new local variable with that name instead, as seen in this example:

fruit = "banana" # this is our global variable def eatFruit(): fruit = "apple" # this is treated as creating a new local variable called "fruit", instead of editing our existing global one print("I ate an "+ fruit) # this prints "I ate an apple" because it's referring to our local "fruit"variable eatFruit() # calling our function prints "I ate an apple" because it's referring to our local copy offruit print(fruit) # printing our global fruit gives us back "banana", not "apple", because we never edited itwithin this function
Code language: Python (python)

As you can see from these examples, the understanding scope is crucial for avoiding errors and confusion when working with variables in Python (or any other programming language).

With practice and experience, it will become second nature for you to figure out which scope a particular piece of data is in and whether or not you can access or edit it from where you are in your code.

In addition, once you start working with more complex programs, understanding scopes will become increasingly important for organizing and structuring your code effectively.

Another example of global variables in Python

Let’s look at an example to help illustrate the difference between global and local variables.

Say we want to write a program that calculates the average of three numbers. We could do this by writing a function that takes in three arguments (the three numbers we want to find the average of) and returns the average.

Our function might look something like this:

def average(num1, num2, num3): avg = (num1 + num2 + num3)/3 return avg
Code language: JavaScript (javascript)

Now, let’s say we also want our program to print out the average number. We could write another function to do this, or we could add it to our existing function like so:

def average(num1, num2, num3): avg = (num1 + num2 + num3)/3 print("The average is", avg) return avg
Code language: PHP (php)

But what if we want to use the average somewhere else in our code outside of the average function?

For example, what if we wanted to print out “The average is above 50” if the average of the three numbers was indeed above 50?

We couldn’t do this with our current code because the avg variable only exists within the scope of our average function- it doesn’t exist outside of it. This is where global variables come in handy.

We could rewrite our code like this:

avg = 0 #this defines avg as a global variable def average(num1, num2, num3): global avg #this tells Python that we want to use the global avg variable inside of our function avg = (num1 + num2 + num3)/3 #this calculates the new value for avg and assigns it to the global variable return avg
Code language: Python (python)

Now we can use the avg variable outside of our function!

Let’s add some code to do what we wanted before:

def main(): #define main function first_number = float(input("Please enter your first number: ")) #get input from user and convert data type to float number second_number = float(input("Please enter your second number: ")) #get input from user and convert data type to float third_number = float(input("Please enter your third number: ")) #get input from user and convert data type to float result = average(first_number, second_number, third_number) #call average function and store result if result > 50: #if statement prints out desired message if result meets condition print("The average is above 50") else: #else statement prints out desired message if result does not meet condition print("The average is below 50") main() #call mainfunction
Code language: Python (python)


In conclusion, a global variable is a variable that is defined outside of all functions in a program. Local variables are variables defined inside functions. Global variables can be called by any function in the program while local variables can only be called inside their own respective functions. Thanks for reading! I hope this helped clear things up for anyone who was confused about global vs local variables in Python.

Andy Avery

I really enjoy helping people with their tech problems to make life easier, ​and that’s what I’ve been doing professionally for the past decade.

Recent Posts