Search code examples
pythonschedule

Updating a variable in Python Schedule


With the python schedule, I am unable to feed the updated output back to the variable. Is there a smart way to achieve this?

x = 10

from schedule import every, repeat, run_pending
import time

@repeat(every(3).seconds, x)
def yee(x):
    x = x * 2
    print(x)
    return x

while x != 80:
    run_pending()
    time.sleep(1)

Currently I am getting output like this:

20
20
20

But I am hoping to get output like this:

20
40
80

Solution

  • If you want to update a global, then you have to use the global statement. Right now, you set the global x once (to 10). The name x within your function is entirely local. And there's no point in returning anything.

    @repeat(every(3).seconds)
    def yee():
        global x
        x *= 2
        print(x)