Search code examples
pythonconditional-statementsoperators

Compare string and integer in same if statement


I have a program that takes input from the user. I want to display an invalid option message if the input is a string or it is not a number between 1 to 4. I want to check all these 3 conditions in a single if statement.

ask_option = input("Your option: ")

if int(ask_option) != int and (int(ask_option) < 1 or int(ask_option) > 4):
    print("Not a valid option")

I feel the int(ask_option) != int is incorrect. But is it possible to fulfill all these 3 in a single if statement?

My code fulfills the criteria to choose between 1-4 but doesn't work to check string input. Please help


Solution

  • input() will always return a string unless you explicity convert it. So using ask_option = int(input("Your option: ")) will already satisfy checking if ask_option is an integer as an exception will be raised otherwise.

    As for evaluating the integer, you can accomplish this in a single line such as:

    if not 1 <= ask_option <= 4:
       print("Not a valid option")