如何在随机数达到0时结束循环

时间:2018-09-21 14:47:05

标签: python python-2.7 random time

我不擅长python,找不到我能理解的解决方案。 我试图让程序在随机倒计时完成后输出“随机计时器已结束”。

import time
from random import randint

RandomTimer = randint(1,10) #picks random number of seconds for countdown
while RandomTimer > 0:
    time.sleep(1)
    RandomTimer - 1  #reduces random number every second until it reaches 0
print("random timer ended")

这里的代码不起作用,因为倒计时似乎永远不会结束,即使在10秒后也是如此。我知道我在做错事,但可以解决。

2 个答案:

答案 0 :(得分:1)

您需要更新RandomTimer

import time
from random import randint

RandomTimer = randint(1,10)
while RandomTimer > 0:
    time.sleep(1)
    RandomTimer -= 1
print("random timer ended")

以上代码将RandomTimer - 1行更改为RandomTimer -= 1

答案 1 :(得分:0)

在Python中,变量包含对对象的引用。

要“更改”变量,可以更改引用的对象。或引用其他对象。 您没有更新变量:

  

“就地”更新:

import time
from random import randint

RandomTimer = randint(1,10) #picks random number of seconds for countdown
while RandomTimer > 0:
    time.sleep(1)
    RandomTimer -= 1  #reduces random number every second until it reaches 0
print("random timer ended")

或创建一个新引用:

RandomTimer = randint(1,10) #picks random number of seconds for countdown
while RandomTimer > 0:
    time.sleep(1)
    RandomTimer = RandomTimer -1  #reduces random number every second until it reaches 0
print("random timer ended")