Compare string and integer in same if statement

Question:

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

Asked By: user863975

||

Answers:

If you try to convert string input into an int, the program will throw ValueError.

ask_option = input("Your option: ")

try:
   val = int(ask_option)
   if val <= 1 or val => 4:
    print("Not a valid option!")
except ValueError:
   print("Not a valid option!")
Answered By: Bipul singh kashyap

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")
Answered By: Teejay Bruno
ask_option = input("Your option: ")
if len(ask_option) != 1 or ask_option < '1' or ask_option > '4':
    print("Not a valid option")
else:
    print( "valid option")

Edit:

OP: "I want to display an invalid option message if the input is a string or it is not a number between 1 to 4."

Therefore we need to accept values ranging from 1 - 4

We know that input() accepts everything as a string

so in the if statement

first condition: len(ask_option) != 1

We invalidate any string whose length is not equal to 1 ( since we need to accept values ranging from 1-4 which are of a length 1 )

And now we are left to deal with the input value whose length is just 1 which could be anything and will be checked with the next 2 conditions.

second and third condition: ask_option < '1' or ask_option > '4'

We do string comparison ( which is done using their ASCII values )

more on string comparison: String comparison technique used by Python

I would not recommend using this approach since it’s hard to tell what it does on the first look, so it’s better if you use try except instead as suggested in other answers.

See this solution as just a different approach to solve OP’s problem ( but not recommended to implement. )

Answered By: Kaushik R Bangera