User Input Validation using Try|Except

Viewed 49

I'm pretty new to Python, Lately I was working on user input validation with nested try/except. My code is as below:

def user_input():
try:
    myinput = 0
    myinput = float(input("Enter a numberic value:"))
    if myinput > 10:
        raise ValueError('Expect a number between 0 and 10')
    #print(myinput)
    return myinput
except:
    print("something went wrong try again!")
    user_input()

print(user_input())

Though it was almost working as expected, I noticed an issue. When I call this function and at the initial stage if I pass an acceptable input the function returns the correct numeric value.

But when I try to input a false value initially and subsequently passing the correct value, the function seems not returning the numeric value. I tried to print the return output inside the function, there I'm getting the expected value.

Thanks in Advance

1 Answers

Try return user_input() instead of user_input() in the except block.

Related