-1

Okay, so maybe this topic has already been answered in another Stock Exchange topic directly or indirectly, but I couldn't find one, so if you do find an appropriate post with answer that you think works, please link me too that post.

Below is my code:

while True:
    example=input('Enter something')
    if example=='Hi' or 'Bye':
        print('Yay!')
    else:
        print('Something else.')

When example does not result in the if statement resulting in True, (if I don't enter 'Hi' or 'Bye' into example), it fails to print the else statement and it instead, it will print the return greeting in my if statement. Why is this? Is this called short circuiting? And most importantly, how do I fix this? I'd like to know this because otherwise I would have to make a separate elif statement, which takes a lot more code.

Please try to explain your answers in using basic terminology. By the way, I'm using Python 3.4.3.

TheCodingFrog
  • 3,406
  • 3
  • 21
  • 27

2 Answers2

2

To add onto what was said above, you can also do:

if example in ['Hi', 'Bye']:

This is a bit more practical if the list is longer.

Jackie Jones
  • 100
  • 1
  • 12
1

Use a tuple as they are quick and cheap to create for small lengths rather than a list:

if example in ('Hi', 'Bye'):

If you were going to do a large comparison (larger than the example below!) on a lot of different options then use a set as a set can only contain unique entries and is better optimised for searching across:

if example in {'Hi', 'Bye', 'Hello', 'Goodbye', 'Adios', 'Bonjour'}:

Off Topic Often text inputs can contain unexpected cases. Adding .lower() and comparing to lowercase strings will avoid that...

if example.lower() in ('hi', 'bye'):
Alexander McFarlane
  • 10,643
  • 9
  • 59
  • 100