简体   繁体   中英

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!!

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.

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.

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"

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')

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM