python-3.x - 在 9 秒内打印尽可能多的数字,然后在第 10 秒打印“-1”
问题描述
所以,我有兴趣在 9 秒内打印尽可能多的数字,然后在第 10 秒打印 -1。我有一个 while 循环每 10 秒打印 -1 和一个 while 循环每 9 秒打印 0 到 10 之间的任何随机数。我正在这样做。
我的问题有两个:
- 我不确定如何创建一个可以在 9 秒内打印尽可能多的数字(取决于计算速度)的循环
- 我不确定如何将它与循环放在一起以每 10 秒打印一次 -1。
非常感谢大家!
解决方案
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 并在其他时间打印随机整数。所以上面的代码可以满足你的目的。
希望这可以帮助 !
推荐阅读
- applescript - 使用 Applescript 控制 Quicktime
- javascript - 使用正则表达式查找与输入字符串中的一组单词/代码匹配的单词
- flutter - 找到一种方法将查询参数附加到颤振 InAppWebView 中的链接打开
- heroku - Heroku 数据库连接
- java - 如何在 JpaRepository 中使用枚举参数?
- typescript - 如何在 GitHub Actions 中缓存纱线包
- excel - 在另一个刚刚打开的工作簿中运行宏
- logging - 如何删除普罗米修斯日志文件?无法使用 systemd 启动 prometheus
- javascript - Socket.io:如果在快速路由中使用,事件会触发两次
- powershell - 鲍尔斯希尔。Microsoft.SqlServer.Management.Smo