Or operator confusion python

125 views Asked by At

I am making a quick zork game but I ran into this problem using the "or" operator. I thought this would be simple but I can't figure out why this isn't working. Right now if you type in "n" you should get "this works" because it equals the string "n". Instead it prints out "it works" AND "this works" so obviously I used "or" wrong.

   x=0
    while x<20:
        response = input("HI")
        if response!= 'n':
            print("it works")

        if response == 'n':
            print("this works")
        x+=1

Before using or it works

x=0
while x<20:
    response = input("HI")
    if (response!= 'n') or (response != 's'):
        print("it works")


    if (response == 'n') or (response == 's'):
        print("this works")
    x+=1

After using or it prints both out. It probably something obvious -.-

2

There are 2 answers

5
mgilson On BEST ANSWER

the expression:

(response != 'n') or (response != 's')

will always be True for any string response. If response is 'n', then it isn't 's'. If it's 's', then it isn't 'n'. If it's anything else, then it's not 's' and it's not 'n'.

Perhaps you meant to use and there?

0
thefourtheye On

If response is either n or s, both the conditions will be met. The best way to do this would be

if response in ('n', 's'):
    print ("it works")
else:
    print ("this works")