首页 > 解决方案 > 在 9 秒内打印尽可能多的数字,然后在第 10 秒打印“-1”

问题描述

所以,我有兴趣在 9 秒内打印尽可能多的数字,然后在第 10 秒打印 -1。我有一个 while 循环每 10 秒打印 -1 和一个 while 循环每 9 秒打印 0 到 10 之间的任何随机数。我正在这样

我的问题有两个:

  1. 我不确定如何创建一个可以在 9 秒内打印尽可能多的数字(取决于计算速度)的循环
  2. 我不确定如何将它与循环放在一起以每 10 秒打印一次 -1。

非常感谢大家!

标签: python-3.xrandomnumbers

解决方案


time为此,您可以使用python 模块。检查以下代码以供参考:

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))  

输出 :

-1
-1

-1上面的代码大约每 10 秒打印一次。我本可以做到(time.time()-start_time)%10==0的,但这种情况很少会被评估为 True。

所以,我和(time.time()-start_time)>=10*multiplier. 此代码将在每 10 秒后打印-1(相差几毫秒)。

您不需要time.sleep(10)像在图像中显示的那样使用,因为这就像暂停循环一样。但是,您希望每 10 秒连续运行循环打印 -1 并在其他时间打印随机整数。所以上面的代码可以满足你的目的。

希望这可以帮助 !


推荐阅读