Random.randint在Python中不生成随机数
此函数(Random.randint在Python中不生成随机数,python,if-statement,random,while-loop,Python,If Statement,Random,While Loop,此函数(playCraps())应选择1和6之间的两个随机整数,求和,并返回True或False值,保存在x中 出于某种原因,每次我运行程序时,它总是返回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)
playCraps()
)应选择1和6之间的两个随机整数,求和,并返回True
或False
值,保存在x
中出于某种原因,每次我运行程序时,它总是返回
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))
为什么会发生这种情况?如何解决这个问题呢?当x==0:循环时,在
x
等于True
之前,您不会退出。
因为0==x
你总是得到True
,因为你的while
循环将执行,即使x
为False
。0在Python中是一个伪值。例如:
>>> x = False
>>> if x == 0:
print 'x == 0 is falsy'
x == 0 is falsy
因此,无论发生什么情况,您的循环最终都会给出True
。一个可能的解决方案是定义:
x = False
while not x:
...
这不是有效的python代码。请您修复缩进,以便我们跟踪错误?缩进正确吗?应该是,而不是x
,这是我的问题,我可以看出我现在做错了什么。谢谢大家!@RLFRICK很高兴,请考虑