Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Random.randint在Python中不生成随机数_Python_If Statement_Random_While Loop - Fatal编程技术网

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很高兴,请考虑