如何在 python 中正确使用 sleep with print 和 random

How to properly use sleep with print and random in python

我是新手,我一直在尝试构建一个随机倒数计时器,它会在 0 到 10 之间选择一个数字,然后从所选整数开始计数到零。所有同时打印倒计时。但是,我不断收到来自 sleep() 的错误。

import random
import time

x = random.randint(0,10)

y = time.sleep(x)

while y != 0:
    print(y)

这段代码可以满足您的需求。简单地说,在 while 循环中,我们 sleep 1 秒并递减 x,直到我们到达 x=0.

import random
import time

x = random.randint(0, 10)
print("Starting countdown!")
while x>0:
   print(x)
   time.sleep(1)
   x-=1
print("Countdown ended!")

这将满足您的需求。 sleep 间隔是数字之间的延迟,所以它应该是常量:

from random import randint
from time import sleep

x = randint(0,10)

def countdown(start_time):
    print("Counting from " + str(start_time))
    for n in range((start_time + 1)):
        y = start_time - n
        print(y)
        sleep(1) # Assumes 1 second delay between numbers

if __name__ == "__main__":
    countdown(x)

这可能对你有帮助:

import random
import time

countdown = random.randint(0,10)

for i in reversed(range(countdown)):
    print(str(i) + ' sec left')
    time.sleep(1)