【问题标题】:Random.randint not generating a random number in PythonRandom.randint 不在 Python 中生成随机数
【发布时间】:2016-05-24 22:07:18
【问题描述】:

这个函数 (playCraps()) 应该选择 1 到 6 之间的两个随机整数,将它们相加,然后返回 x 中保存的 TrueFalse 值。
出于某种原因,每次我运行程序时,它总是返回 True 和 7 或 11。

import random

wins = [7, 11]
losses = [2, 3, 12]

def playCraps():
    x = 0 
    while x == 0:
       sumDice = random.randint(1,6) + random.randrange(1,6) 
       if sumDice in wins:
           x = True 
       elif sumDice in losses:
           x = False 
       else:
           sumDice = 0 
print("The sum of the dice was " + str(sumDice)) 
print("So the boolean value is " + str(x))

为什么会这样?如何解决这个问题?

【问题讨论】:

  • 这不是有效的 python 代码。能否请您修复缩进,以便我们追踪错误?
  • 缩进是否正确?

标签: python if-statement random while-loop


【解决方案1】:

你总是得到True,因为即使xFalse,你的while 循环也会执行。 0 是 Python 中的 falsy 值。示例:

>>> x = False
>>> if x == 0:
        print 'x == 0 is falsy'
x == 0 is falsy

因此,无论如何,您的循环最终都会给出True。一个可能的解决方案是定义:

x = False 
while not x:
    ...

【讨论】:

  • 应该是while not x
  • 这是我的问题,我现在可以看到我做错了什么。谢谢!
  • @rlfrick 很高兴它成功了,请考虑accepting the answer
【解决方案2】:

x 等于True 之前,您不会退出while x == 0: 循环。 因为0 == x

【讨论】:

    猜你喜欢
    • 2013-11-13
    • 2014-11-16
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多