有没有办法让python程序等待几秒钟?我正在制作无限数打印机,但它太快而无法阅读



我不知道如何让我的程序等待几秒钟,以便我可以实际读取它python中是否有等待函数,或者是否有相应的模块?我没有办法在窗口中运行它,因为我使用的是学校的chromebook。

My Code:

from random import randint
while True:
a = randint(0,999999)
b = randint(0,999999)
c = randint(0,999999)

if (a <= b) or (a <= c):
print("variable 'a' has been printed")
print(a)

elif (b <= a) or (b <= c):
print("variable 'c' has been printed")
print(b)

elif (c <= a) or (c <= b):
print("variable 'c' has been printed")
print(c)

elif (a == b):
print("Combo of 'a' + 'b'")
print(a + b)

elif (a == c):
print("Combo of 'a' + 'c'")
print(a + c)

elif (b == c):
print("Combo of 'b' + 'c'")
print(b + c)

How to make it wait?

使用sleep(),它会在几秒钟内获取参数。

from random import randint
from time import sleep
while True:
a = randint(0,999999)
b = randint(0,999999)
c = randint(0,999999)

if (a <= b) or (a <= c):
print("variable 'a' has been printed")
print(a)
sleep(1)

elif (b <= a) or (b <= c):
print("variable 'c' has been printed")
print(b)
sleep(1)

elif (c <= a) or (c <= b):
print("variable 'c' has been printed")
print(c)
sleep(1)

elif (a == b):
print("Combo of 'a' + 'b'")
print(a + b)
sleep(1)

elif (a == c):
print("Combo of 'a' + 'c'")
print(a + c)
sleep(1)

elif (b == c):
print("Combo of 'b' + 'c'")
print(b + c)
sleep(1)

你需要像上面那样从time导入它。

或者,如果在while循环的末尾只有一个sleep()函数,而不是几个sleep()函数,它将更有效和可维护。下面是上面代码的一个更好的示例。谢谢Max的建议。

from random import randint
from time import sleep
while True:
a = randint(0,999999)
b = randint(0,999999)
c = randint(0,999999)

if (a <= b) or (a <= c):
print("variable 'a' has been printed")
print(a)

elif (b <= a) or (b <= c):
print("variable 'c' has been printed")
print(b)

elif (c <= a) or (c <= b):
print("variable 'c' has been printed")
print(c)
elif (a == b):
print("Combo of 'a' + 'b'")
print(a + b)

elif (a == c):
print("Combo of 'a' + 'c'")
print(a + c)
elif (b == c):
print("Combo of 'b' + 'c'")
print(b + c)
sleep(1)

您可以在需要等待的代码中引入sleep。

import time
time.sleep(5) # sleep for 5 seconds

链接到文档time.sleep()

最新更新