Home > front end >  How can I simplify this code and make it easier to read?
How can I simplify this code and make it easier to read?

Time:02-01

decision = input("Would you like to try again?(y/n) (or 'Help' for instructions")
if decision != "y" or decision != "n" or decision != "Help:":
    print("This input is not readable! Try again!")

I'm working on a program. I just wrote some code, so it's not too long. This is a different code from what I'm currently working on. But it's the same question:

What's the easiest way to write the if statement in one line? Is there any way I can get all of that in one line?

If this is not enough information let me know.

CodePudding user response:

You can shorten it to

if decision not in ["y", "n", "Help"]:

but it's probably a matter of opinion whether three explicit inequality checks is too many.

CodePudding user response:

You can do this by comparing the input to a list like the following:

CORRECT_INPUTS = ["y", "n", "help:"]

if decision.lower() not in CORRECT_INPUTS:
    print("This input is not readable! Try again!")

You can extend this list easily and it will compare the input to the lowercase variant, so it's a bit more robust.

  • Related