2

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?

2
  • 1
    This is not valid python code. Could you please fix the indentation, such that we can track down the error? Commented Feb 13, 2016 at 20:30
  • Is the indentation correct? Commented Feb 13, 2016 at 20:30

2 Answers 2

2

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:
    ...
Sign up to request clarification or add additional context in comments.

3 Comments

should be while not x
This was my issue, and I can see what I was doing wrong now. Thank you!
@rlfrick Glad it worked, please consider accepting the answer
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.