Avatar ·

Global variables in Python: save local variable from function call to call

📁 function, Advanced Python Topics, AI, work

I have a function that needs to save a value from call to call, and this value is only used inside this function. How to properly use global variables in Python? I tried to write something like this:

someGlobalVar = 0def incrimentGlobalVar()    someGlobalVar = someGlobalVar + 1

But this code doesn't work. Are there other ways to solve this problem?

Avatar ·

There are several ways to implement this behavior.

Global variables

The first thing that comes to mind is using global variables.
It's important to note that global variables are readable

def func1():    print(x)x = 10func1()   # 10

but simple write access is not allowed:

def func2():    y = 20    # creates a local variable, not modifies the global oney = 10func2()print(y)

Log in to leave an answer

Blogs