简体   繁体   中英

Random.randint not generating a random number in Python

This function ( playCraps() ) is supposed to choose two random integers between 1 and 6, sum them up, and return a True or False value held in x .
For some reason, each time I run the program, it always returns True with either 7 or 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))

Why does this happen? And how can this be fixed?

You always get True because your while loop will execute even if x is False . 0 is a falsy value in Python. Example:

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

So your loop will eventually give True no matter what. A possible solution will be to define:

x = False 
while not x:
    ...

You won't exit the while x == 0: loop until x is equal to True . Because 0 == x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM