Vale
Vale

Reputation: 1033

Is there a way to make a "Not a number" if statement in Python?

Forgive me if this a stupid question, but I searched everywhere and couldn't find an answer due to the wording of the question.

Is there a way to have a "Not a number" value in an if statement in Python?

Say for example you have a menu like this:

For free examples - Press 1
For worse free examples - Press 2

And I wanted to write an if statement, or elif statement, that says something along the lines of:

elif menu_Choice != #:
    print("This menu only accepts numerical input. Please try again.\n")
    menu_Choice = input("\n")

Can I do so? If so, how?

Upvotes: 1

Views: 1174

Answers (3)

Joran Beasley
Joran Beasley

Reputation: 113930

feeding of the other answer

choices = {
  "1": free_samples_list,
  "2" : other_list,
}
choice = input(...)
while choice not in choices:
     print ("Invalid choice:")
     choice = input(...)

this allows you to encapulate both data validation and selection

Upvotes: 1

Totem
Totem

Reputation: 7349

Why not say something like:

if menu_choice == "1":
    do this
elif menu_choice == "2":
    do this
else:
    print("Invalid input...!")

You could also do:

menu_choice = ""

while menu_choice not in ["1", "2"]: # not ideal with lots of choices
    print("This menu only accepts numerical input. Please try again.\n")
    menu_Choice = input("\n")

Then go to your if statments

EDIT:

with regards to your comment, you could do:

# you could make range as big as you like..
choices = [str(i) for i in range(1, 11)] #['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

while menu_choice not in choices:
    print("That input wasn't valid. Please try again.\n")
    menu_Choice = input("\n")

I made the list choices with a list comprehension

Upvotes: 4

mhlester
mhlester

Reputation: 23211

There is the .isdigit() string method.

elif not menu_Choice.isdigit():
    print("This menu only accepts numerical input. Please try again.\n")
    menu_Choice = input("\n")

Keep in mind this doesn't check if it's in the right range, just if it's numeric. But by the time you've gotten this far, maybe you could just use else?

Upvotes: 4

Related Questions