0

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()
2
  • Thank you! I got it to work as desired. Commented Oct 21, 2015 at 0:59
  • If my answer worked for you, please accept it, and consider doing the same for all your previous questions too. Commented Oct 21, 2015 at 6:36

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Oops, this comment was intended for the second answer.
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.