1

Here is a part of my code where the problem is. It doesn't matter what the input is, the script will end when I enter something.

It should restart when i enter "yes" or "y" Without the OR it works without problem

else:
    if number == rndnum:
        print "Congratulations! You won."
        print "Do you want to replay?"
        answer = raw_input("Type y (yes) or n (no): ")
        dialog = 1
        while dialog == 1:
            if answer == "n" or "no":
                replay = 0
                dialog = 0
            elif answer == "y" or "yes":
                dialog = 0
            else:
                answer = raw_input("Type y (yes) or n (no): ")
        loop = 0 #Will overdo loop var and stop the loop
Matt
  • 161
  • 2
  • 9

2 Answers2

4
if answer == "n" or "no":

is interpreted by Python as:

if (answer == "n") or ("no"):

Which is always true, because the second condition in your or clause is always True (non-empty strings in Python are truthy, which means they evaluate to True in a condition):

>>> bool("no")
True

What you need is one of:

if answer in ("n", "no"):

# or 

if answer == "n" or answer == "no":

Th same goes for "yes", of course.

Thomas Orozco
  • 53,284
  • 11
  • 113
  • 116
0

Adjust your code like this:

if answer == "n" or answer == "no":
    # ...

and:

elif answer == "y" or answer == "yes":
    # ...

a or b, where a and b are strings and not both the empty string, will always evaluate to True in a boolean context, demo:

>>> '' or 'x'
'x'
>>> 'y' or 'x'
'y'
>>> '' or ''
''
>>> if 'x': print('hi')
... 
hi
>>> if '': print('hi')
... 
>>>

The first two expressions will evaluate to True.

timgeb
  • 76,762
  • 20
  • 123
  • 145