Reputation: 75
I'm making a little gag program that outputs a bunch of random numbers onto my Ubuntu terminal until the number meet a certain condition, at which point access granted
is printed.
However, I'd like to stop the Timer loop once that condition is met, and I don't know how.
Here's the code below:
import random
import threading
def message():
tt = threading.Timer(0.125, message).start()
num = str(random.randint(137849013724,934234850490))
print(num)
if num[3] == "5" and num[6] == "7":
print("access granted")
message()
Upvotes: 0
Views: 1070
Reputation: 49320
You don't need to create a threaded timer for that. Just loop an appropriate quantity of random numbers with a delay:
import time
import random
for i in range(10):
print(random.randint(1,10), flush=True)
time.sleep(0.1)
Upvotes: 1
Reputation: 47770
Timer
objects call their function once after a delay, that's it. The reason there's a "loop" is because the function you're telling the timer to call is what's setting up the next timed call to itself. So all you need to do is NOT do that once your condition is met:
def message():
num = str(random.randint(137849013724,934234850490))
print(num)
if num[3] == "5" and num[6] == "7":
print("access granted")
else:
threading.Timer(0.125, message).start() # <== moved
Upvotes: 3