Input validator function does not accept valid input

Question:

The following function asks for a user input until it receives an input of 1 or 2. I would like to know if there is a cleaner solution that does not involve the try/except statement or recursion.

def input_params(prompt):
    while True:
        try:
            user_input = int(input(prompt))
            if user_input == 1 or user_input == 2:
                return user_input
            else:
                print("Invalid Input")
                input_params(prompt)
        except ValueError:
            pass
Asked By: PythonProgrammer

||

Answers:

Skip the recursion, and use the ValueError to continue the loop before checking the integer value.

def inputParam(prompt):
    while True:
        x = input(prompt)
        try:
            n = int(x)
        except ValueError:
            print("Invalid integer input")
            continue

        if n == 1 or n == 2:
            return n

        print("Enter 1 or 2")
Answered By: chepner

You can do like this:

def inputParams(prompt):
    while True:
        x = input(prompt)
        if x.isnumeric():
            x = int(x)
            if x in [1, 2]:
                return x
            else:
                print("Invalid input!")
        else:
            print("please input only number")
Answered By: CYBER HK

If you want to avoid try-except block entirely, you can use the following code. It’s not common to use contextlib.suppress but in this isolated situation, it can work out nicely.

import contextlib

def inputParams(prompt):
    while True:
        with contextlib.suppress(ValueError):
            if (x := int(input(prompt))) in [1, 2]:
                return x
        print("Invalid input, try again.")

print(f"You entered {inputParams('Enter 1 or 2: ')}.")
Answered By: sanitizedUser

Instead of taking it as list [1,2]. I have done with : if int(x) == 1 or int(x) == 2:

Code :

def userInput():
    while True:
        x = input("Enter value : ")

        if x.isnumeric() :
            if int(x) == 1 or int(x) == 2:
                return x
        else:
            print('Not Number')

userInput()

Feel free to correct me if anything wrong in above code

Answered By: codeholic24
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.