Lisa G Lisa G - 1 year ago 53
Python Question

The IF statement is ignoring or not accepting the logical operator 'or'

# asks the question and gives the choices
choice=input('what is your favourite colour? press 1 for red, 2 for blue, 3 for yellow or 4 to quit')
# if the responder responds with choice 1 or 2,3,4 it will print this
if choice=='1' or 'one':
print('red means anger')

elif choice=='2'or 'two':
print('blue represents calmness')
elif choice=='3' or 'three':
print('yellow represents happiness')
elif choice=='4' or 'four':
print('it was nice meeting you. goodbye.')
print('sorry incorrect answer please try again.')

One of my students wrote this and I can't seem to get it working.
HELP! It keeps repeating red means anger. If I comment out the 'or',
it works but why can't she use 'or'? I want her to add a loop but only
if this works first.

Answer Source

when you have statement like

if choice=='1' or 'one':

it will be treated as

if (choice=='1') or 'one': 

'one' is always evaluate to True, thus the if condition is always fulfill, what you need is as below, bracket to make things clearer

if (choice=='1') or (choice=='one'): 

Alternatively, when you have multiple OR statement to be check against a value, can consider put all the check value in a list and use in like below, this look cleaner to me when the value to check increasing

if choice in ['1', 'one', '2', 'two', '3', 'three']: