为什么random.choice()有时不做任何选择?
我正在尝试创建一些逻辑,可以可靠地在两件事之间进行选择。但是下面的代码似乎有一些严重的错误,因为通常没有选择。
import random
while True:
if random.choice([0, 1]) == 0:
print("Right")
elif random.choice([0, 1]) == 1:
print("Left")
else:
print("Why do we ever reach the else?")
输出如下所示:
$ python3 random.choice.broken.py
Why do we ever reach the else?
Why do we ever reach the else?
Left
Why do we ever reach the else?
Left
Right
Left
Left
Why do we ever reach the else?
Why do we ever reach the else?
Right
Why do we ever reach the else?
Left
Right
Right
Why do we ever reach the else?
Left
Right
Left
Left
Right
Left
Right
Right
Right
Why do we ever reach the else?
Left
Why do we ever reach the else?
Why do we ever reach the else?
Right
我相信一定有一个合理的解释。但是我无法在网上或文档中找到它。谢谢。
回答
这是导致这种情况的代码的性质。您在输入条件后做出随机选择。理想情况下,您应该在输入IF条件之前做出选择,然后再参考它。
import random
while True:
ch = random.choice([0, 1]) #<-----
if ch == 0:
print("Right")
elif ch == 1:
print("Left")
else:
print("Why do we ever reach the else?")
Left
Right
Right
Right
Right
Left
Right
Left
Right
Left
Right
Left
Left
Left
Right
Left
Right
Left
Left
Left
Left
分析您当前的代码行为
为了进一步解释,让我们分析一下为什么您会在当前代码中到达特定的打印语句 -
print("Right")- 如果您的第一选择等于 0print("Left")- 如果您的第一选择不等于 0,而您的第二选择等于 1。print("Why do we ever reach the else?")- 如果您的第一选择不等于 0,而您的第二选择不等于 1。
注意:由于您
random.choice([0, 1])在条件本身中提及而不将其存储在变量中,因此选择的每个实例都是一个单独的实例。因此,您的第一个 random.choice 与第二个 random.choice 不同。
希望这也解释了当前的行为。
- ....nice explanation...