-3

I am making this game where the user has to choose from 5 options. So, he must type any number from 1 to 5 to choose an option. Now here is the problem I am facing, I just can't figure out a way in which the user cannot type in any other character except the int numbers from 1 to 5, and if he does type in a wrong character, how should I show his error and make him type in the input again? Here is what I've tried:

def validateOpt(v):
   try:
      x = int(v)
      if int(v)<=0:
         x=validateOpt(input("Please enter a valid number: "))
      elif int(v)>5:
         x=validateOpt(input("Please enter a valid number: "))
         return x
   except:
      x=validateOpt(input("Please enter a valid number: "))
      return x

Here validateOpt is to validate the number for the option, i.e., 1,2,3,4,5. It works fine, but whenever I type 33,22, 55, or any other int number from 1 to 5 twice (not thrice or even four times, but only twice), it doesn't show any error and moves on, and that, I suppose, is wrong. I am just a beginner.

NISH3003
  • 92
  • 1
  • 7
  • 2
    every time you are in a function and call the same function you should pause and think twice - most of the time recursion is not the way to go. – Patrick Artner Aug 17 '20 at 13:02

4 Answers4

1

You can do this with a while loop, something like this should be a good start:

def getValidInt(prompt, mini, maxi):
    # Go forever if necessary, return will stop

    while True:
        # Output the prompt without newline.

        print(prompt, end="")

        # Get line input, try convert to int, make None if invalid.

        try:
            intVal = int(input())
        except ValueError:
            intVal = None

        # If valid and within range, return it.

        if intVal is not None and intVal >= mini and intVal <= maxi:
            return intVal

Then call it with something like:

numOneToFive = getValidInt("Enter a number, 1 to 5 inclusive: ", 1, 5)
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0

use a while loop instead of recursion, you can check the user data and return if its valid, although you might want to consider a break out clause should the user want to exit or quit without a valid input.

def get_input(minimum, maximum):
    while True:
        try:
            x = int(input(f"please enter a valid number from {minimum} to {maximum}: "))
            if minimum <= x <= maximum:
                return x
        except ValueError as ve:
            print("Thats not a valid input")
            

value = get_input(1, 5)
Chris Doyle
  • 10,703
  • 2
  • 23
  • 42
-2

Use for loop in the range between 1 and 5

-3

Try this code, it will keep prompting user till he enters 5, note that this may cause stackoverflow if recursion is too deep:

def f():
    x = input("Enter an integer between 1 and 5:")

    try:
        x = int(x)
        if x<=0 or x>5:
            f()
    except:
       f()

f()
Shiv
  • 1,912
  • 1
  • 15
  • 21