我是新手,我一直在尝试构建一个随机倒数计时器,它选择0到10之间的数字,并从所选整数计数到零。同时打印倒计时。但是,我一直从睡眠中获得错误()。
import random
import time
x = random.randint(0,10)
y = time.sleep(x)
while y != 0:
print(y)
答案 0 :(得分:5)
这可能会对您有所帮助:
import random
import time
countdown = random.randint(0,10)
for i in reversed(range(countdown)):
print(str(i) + ' sec left')
time.sleep(1)
答案 1 :(得分:0)
此代码可以满足您的需求。简单地说,在循环内部我们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!")
答案 2 :(得分:0)
这将满足您的需求。 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)