0

So I was creating a Python project, let's just keep the details secret. The user can choose between two features to run and this choice is collected in a variable using 'input' function. Everything goes right and there are no errors in the whole file but, the if-elif-else statement that I'm using doesn't seem to work properly.

initiate = input("Your input here: ")

if 'a' or 'file' in initiate: 
    FileCheck()

elif 'b' or 'word' in initiate: 
    WordCheck()

else:
    print("You have entered an invalid input. Exiting...")
    sleep(5)
    exit

If I give 'a' or 'b' as input, it still runs the 'FileCheck' function. Both functions are properly defined. If invalid input is given, it does run the 'else' part, but not the 'WordCheck' function when the user inputs 'b' or 'word'. The code doesn't throw any errors too. Please help me through this. Thanks!

rioV8
  • 24,506
  • 3
  • 32
  • 49
  • `if any(i in initiate for i in ('a', 'file')):` – Cory Kramer Nov 12 '20 at 14:52
  • @CoryKramer This worked perfectly! Thanks! Could you also explain why it worked? Just so I can learn something instead of just copying and pasting. Thanks again! – Shishir Modi Nov 12 '20 at 14:57
  • 1
    Your code is interpreted as `if ('a') or ('file' in initiate):` where the first value will be `True` because all strings other than empty string `''` will be "truthy". The more verbose way to write it closer to your expression (without using `any`) would be like `if 'a' in initiate or 'file' in initiate: ` In other words the `in` doesn't "chain" like you would mentality do when reading it in english. – Cory Kramer Nov 12 '20 at 14:59

0 Answers0