有没有办法让一个python程序等几秒钟?我正在做一个无限数字打印机,但是读起来太快了

6gpjuf90  于 2022-12-20  发布在  Python
关注(0)|答案(2)|浏览(63)

我不知道如何让我的程序等待几秒钟,这样我就可以真正地阅读它。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?
bvjveswy

bvjveswy1#

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

您需要从时间导入它,因为我上面.
或者,如果你在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)
ws51t4hk

ws51t4hk2#

您可以在代码中任何需要等待的地方引入睡眠。

import time

time.sleep(5) # sleep for 5 seconds

链接到文档time.sleep()

相关问题