user1594147
user1594147

Reputation: 37

Python 2 - How do I use 'or'?

I'm really new to python, and I've just made a small program. If you type in "Hello" or "hello", and it will say "working", if you type in anything else it will say "not working". Here's the code I have so far:

print "Type in 'Hello'"
typed = raw_input("> ")
if (typed) == "Hello" or "hello":
   print "Working"
else:
    print "not working"

The code isn't working, no matter what I submit it will always say "Working", even if I type "jsdfhsdkfsdhjk". It does work if I take out the "or" and "hello", but I would like to to check for both. How can I make the script work?

Thanks a lot!!

Upvotes: 1

Views: 237

Answers (5)

RedBaron
RedBaron

Reputation: 4755

You can do it in two ways (Atleast)

print "Type in 'Hello'"
typed = raw_input("> ")
if typed == "Hello" or typed == "hello":
   print "Working"
else:
    print "not working"

Or use the in

print "Type in 'Hello'"
typed = raw_input("> ")
if typed in ("Hello","hello",):
   print "Working"
else:
    print "not working"

Upvotes: 0

nneonneo
nneonneo

Reputation: 179717

The expressions on either side of or (and and) are evaluated independently of each other. So, the expression on the right side doesn't share the '==' from the left side.

If you want to test against multiple possibilities, you can either do

typed == 'Hello' or typed == 'hello'

(as Hbcdev suggests), or use the in operator:

typed in ('Hello', 'hello')

Upvotes: 2

Kevin London
Kevin London

Reputation: 4728

You may want to try converting typed to lowercase, so you only have to check for one thing. What if they typed "HELLO"?

typed = raw_input("> ")
if typed.lower() == "hello":
    print "Working"
else:
    print "not working"

Upvotes: 2

Paolo Bergantino
Paolo Bergantino

Reputation: 488724

You are checking to see if typed is equal to "Hello" OR if "hello" as a standalone expression evaluates to true (which it does). You don't get to chain multiple values to check against an original variable. If you want to check if an expression is equal to different things, you have to repeat it:

if typed == 'Hello' or typed == 'hello':

Or, something like:

if typed in ['Hello', 'hello']: # check if typed exists in array

Or, something like this:

if typed.lower() == 'hello': # now this is case insensitive.

Upvotes: 13

hcarver
hcarver

Reputation: 7234

if (typed) == "Hello" or "hello": should be if typed == "Hello" or typed == "hello":

The problem at the moment is that or should separate two questions. It can't be used to separate two answers for the same question (which is what I think your expecting it to do).

So python tries to interpret "hello" as a question, and casts it to a true / false value. It happens that "hello" casts to true (you can look up why). So your code really says "if something or TRUE", which is always true, so "working" is always outputted.

Upvotes: 2

Related Questions