1

I made some code that will roll two die and ask the user how many times. After that it will ask the user if they want to play again. For some reason its not breaking out of one of the while loops when it should.

Here's the code:

import random
again = True
rolls = 0
while again == True:
    rolls = float(raw_input("How many times would you like the dice to roll?"))
    while rolls >= 1:
        dice1 = random.randint(1,6)
        dice2 = random.randint(1,6)
        print dice1 , dice2
        rolls = rolls - 1
    again = raw_input("Would you like to play again?")
    if again == "Yes" or "Y" or "yes" or "y":
        again = True
    else:
        again = False

Can any of you guys help me

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

5 Answers5

8

The problem is this line:

if again == "Yes" or "Y" or "yes" or "y":

That evaluates to:

if (again == "Yes") or "Y" or "yes" or "y":

in other words, it's always true. You mean this:

if again in ("Yes", "Y", "yes", "y"):
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
4
if again == "Yes" or "Y" or "yes" or "y":

This isn't doing what you think. It is evaluated as:

if (again == "Yes") or ("Y") or ("yes") or ("y"):

Non-empty strings are logically True, so this entire statement will always be True. You need to compare again to each possible value.

if again in ("Yes", "Y", "yes", "y"):
# or
if again == "Yes" or again == "Y" or again == "yes" or again == "y":
Tim
  • 11,710
  • 4
  • 42
  • 43
1

The line

if again == "Yes" or "Y" or "yes" or "y":

is wrong and will always return True. To fix it, change it to

 if again == "Yes" or again == "Y" or again == "yes" or again == "y":

This is happening because a non-empty string is always truthy. As you are only comparing the string against again in the first expression, in the others you care simply checking to see if the string "Y" is not empty. As that string is hard-coded, it will always be True

It might also be tidier to do

#Uppercase the input and then check if user said yes
if again.upper() in ("YES","Y"):
    do_the_thing()
wdh
  • 1,612
  • 12
  • 16
1

The problem is in your statement

if again == "yes" or "Y" or "yes" or "y"

Statements in python are evaluated to True unless they equal 0 or None which are False.

You would have to do

if again == "Yes" or again == "Y" or again == "yes" etc.

That is because the or "Y" or "yes" is always evaluating to True.

William Denman
  • 3,046
  • 32
  • 34
1

Below work:

import random
again = True
rolls = 0
while again == True:
    rolls = float(raw_input("How many times would you like the dice to roll?"))
    while rolls >= 1:
        dice1 = random.randint(1,6)
        dice2 = random.randint(1,6)
        print dice1 , dice2
        rolls = rolls - 1
    again = raw_input("Would you like to play again?")
    # It correct and more short
    again = True if again in  ("Yes", "Y", "yes", "y") else False
Michael Kazarian
  • 4,376
  • 1
  • 21
  • 25