Reputation: 227
I am trying to schedule to run very x seconds. I am getting mixed up with the simple logic.
import schedule
import time
names = ["1.jpg", "2.jpg", "3.jpg"]
i = 0
def printer():
for item in names:
print(names[i])
i = i+1
schedule.every(5).seconds.do(printer)
while 1:
schedule.run_pending()
time.sleep(1)
what i am trying to get it to do is to print the name 1 then 5 seconds later print name 2 then another 5 seconds later print name 3.
i et the error saying: UnboundLocalError: local variable 'i' referenced before assignment
any ideas?
Upvotes: 0
Views: 694
Reputation: 71562
Your printer
function is broken. If you're trying to have this function print each item in names
, get rid of i
and just do:
names = ["1.jpg", "2.jpg", "3.jpg"]
def printer():
for item in names:
print(item)
If you want the function itself to have a delay between each item, and you only want to run through this once, the simplest thing is to not bother with schedule
at all and just add a sleep
to the loop:
from time import sleep
names = ["1.jpg", "2.jpg", "3.jpg"]
def printer():
for item in names:
print(item)
sleep(5)
printer()
To make it even simpler, you can also get rid of names
and printer
:
from time import sleep
for i in range(1, 4):
print(f"{i}.jpg")
sleep(5)
Upvotes: 3
Reputation: 368
import schedule
import time
names = ["1.jpg", "2.jpg", "3.jpg"]
i = 0
def printer():
global i # here is the fix
for item in names:
print(names[i])
i = i+1 # you trying to change variable in function that already been initialised out of function so you must use global before using the variable
schedule.every(5).seconds.do(printer)
while 1:
schedule.run_pending()
time.sleep(1)
Upvotes: 1