Sobes.tech
Junior — Middle

Explain the purpose and use of global variables in Python.

sobes.tech AI

Answer from AI

In Python, a global variable is a variable declared in the main body of a module, outside of functions and classes, and accessible throughout the module.

To modify the value of a global variable inside a function, the global keyword must be used. Without it, Python will create a local variable with the same name.

Example:

counter = 0  # global variable

def increment():
    global counter  # specify that we want to modify the global variable
    counter += 1

increment()
print(counter)  # Will output 1

Using global variables is convenient for storing state accessible from different parts of the program, but excessive use can lead to debugging and maintenance difficulties.

Explain the purpose and use of global variables in… - sobes.tech