Printing as many numbers as possible in 9 seconds then a "-1" at the 10th second

Viewed 39

So, I'm interested in printing as many numbers as possible in 9 seconds then printing a -1 at the 10th second. I have a while loop to print -1 every 10 seconds and a while loop to print any random number between 0 and 10 every 9 seconds. I am doing like this.

My problem is two-fold:

  1. I'm not sure how to create a loop which can print as many possible numbers (depending on computing speed) in 9 seconds
  2. I'm not sure how to put that together with the loop to print -1 every 10 seconds.

Thanks so much everyone!

1 Answers

You could use time module of python for this purpose. Check the below code for reference :

import time
import random

# Time for which you want the loop to run
time_to_run = 25
# Stores the future time when the loop should stop
loop_for_x_seconds = time.time() + time_to_run
start_time = time.time()
multiplier = 1 # print -1 at 10 second, increment it, so next one will be at 10*multiplier = 20 and so on...

# Loop until current time is less than the time we want our loop to run
while time.time() < loop_for_x_seconds:
    # The below condition will help print -1 after about every 10s
    if (time.time()-start_time)>=10*multiplier:
        print(-1)
        multiplier+=1
    # Commented below just for purpose of showing output of -1 every 10s. Uncomment and use to get random ints printed
    #else:
        #print(random.randint(1,10))  

Output :

-1
-1

The above code will print -1 after every 10 seconds approximately. I could have done (time.time()-start_time)%10==0 ,but this condition would rarely have been evaluated to True.

So, I went with (time.time()-start_time)>=10*multiplier . This code would print -1 after every 10s elapses ( with a difference of few milliseconds ).

You don't need to use time.sleep(10) as you showed in the image, since that would just be like pausing the loop. However, you want to continuously run the loop printing -1 every 10s and random integers other times. So the above code would serve your purpose.

Hope this helps !

Related