Python

How to use global variable in Python

February 13, 2022

How to use global variable in Python

In this article we will learn how to use global variable in Python and also its implications and advantages when using this feature in your software.

global variable in Python cover

What’s up programmer, ok? Let’s learn more about Python and global variables!

When we create a global variable we are expecting to use its value inside functions for example

Something that is like a reference anywhere in the code

To achieve this feat in Python, we need to create a variable in the global scope, that is, at the highest hierarchical level of the code and that is not inside a function.

Then we can use this same variable with the global reserved word in any part of our software

Let’s see a practical example:

test = 1

def printGlobal():
 global test
 print("The value of test is: " + str(test))
 
printGlobal()

Notice that inside the printGlobal function we use the global reserved word

So we are referring to the variable that is in the global scope

The output will be:

The value of test is: 1

Warning!

When using global variables we must pay attention to which functions or parts of the code that depend on them

Because when we create several dependencies of something, it may be that you modify it in a way that is right in one part and damages another part.

This is why global variables are sometimes discouraged, and it is recommended to create a variable for each situation.

A good idea to use a global variable would be in constant form

For example: we have an IP that will never change and we need it in several parts of the code

So it would be a good choice to go for the global variable approach, you know that?

Conclusion

In this article we learned how to use global variable in Python

In Python we can refer to global variables with the global keyword if created at the highest scope of the software

However, we must be extra careful when using this approach, because creating multiple dependencies on a global variable can be a problem.

Wanna learn more about Python? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x