-2

I am stuck on a problem that I am trying to solve. I am only suppose to take int (1-4) from user's input and not take any string/float/etc. I have figured out what to do if a user chooses any integer other than 1-4. However, I am stuck on the part where a user chooses anything other than an integer (i.e string, float, etc). this is what I have done so far:

    def menu():
       my code
    menu()

    # keeps on looping till user have selected a proper selection (1-4)
   selection = int(input("> "))
     if selection == 1: 
       my code
     elif selection == 2: 
       my code
     elif selection == 3: 
       my code
     elif selection == 4: 
       my code
     else:
      print("I'm sorry, that's not a valid selection. Please enter a 
      selection from 1-4. ")
      menu()

Any help would be appriciated. I've been trying to find a solution for hours but got stuck on the last part.

ZeroDigit
  • 5
  • 2

3 Answers3

0

Seeing as you don't appear to be doing any integer operations on the value coming from input - I would personally just leave it as a string.

selection = input("> ")
if selection == "1":
    pass
elif selection == "2":
    pass
#...
else:
    print("I'm sorry...")

By doing this you don't have to deal with that edge case at all.


If you must (for some reason) cast this to an int (like, you're using the value later) then you could consider using exception handling.

try:
    selection = int(input("> "))
except ValueError:
    selection = "INVALID VALUE"

and the continue you on, as your current else statement will catch this and correctly handle it.

Shadow
  • 8,749
  • 4
  • 47
  • 57
0

try this If you make sure that your code allows the user to input only numbers in python:

def numInput():
    try:
        number = int(input("Tell me a number"))
    except:
        print "You must enter a number"
        numInput()

    return number
Mustafa
  • 9
  • 4
0

You can use an infinite loop to keep asking the user for an integer within the desired range until the user enters one:

while True:
    try:
        selection = int(input("> "))
        if 1 <= selection <= 4:
            break
        raise RuntimeError()
    except ValueError, RuntimeError:
        print("Please enter a valid integer between 1 and 4.")
blhsing
  • 91,368
  • 6
  • 71
  • 106