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. )