Search code examples
pythonpython-2.7if-statementexpressionboolean-operations

How to correctly use a boolean operator when analyzing a string in an if-statement?


When I want to check if different part of a string is in a value, it doesn't work if I don't precise the value for each part of string (as in the if statement).

So I guess, the correct way is the one used in my elif statement.

Am I right ? Is there another way to check if some different words have been entered through a raw_input() ?

# we offer a choice
print "What do you want to do ?"
print "1. Listen to radio"
print "2. Turn on TV"

# we ask for an answer through raw_input()
choice = raw_input()

# we use an if-statement to print different strings for each choice provided
if "listen" or "radio" in choice:
    print "Let's listen some music !"
elif "turn" in choice or "TV" in choice:
    print "Let's watch a movie !"
else:
    print "I don't understand what you want to do"
    exit(0)

Thanks. I'm new to python (but I think it is pretty obvious)


Solution

  • This:

    if "listen" or "radio" in choice:
    

    should be:

    if "listen" in choice.lower() or "radio" in choice.lower():
    

    Etc.