Reputation: 41
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?
Upvotes: 2
Views: 941
Reputation: 15310
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:
...
Upvotes: 2
Reputation: 3
You won't exit the while x == 0:
loop until x
is equal to True
.
Because 0 == x
Upvotes: 0