How do I use a function to validate user input within another function?

Question:

I’m guessing there is a quite simple solution to this. How do I get the user input to be validated and then continue on to be used within another function?

When I run this code, it will just insist that the "Invalid option" has been selected. Is there a way to solve this?

Example:

def user_input():
    while True:
        try:
            option = int(input("Enter an option: "))
            break
        except ValueError:
            print("Invalid input. Please enter a number between 1 and 3.")
    
    if option < 1:
        print("Invalid value. Please enter a non-negative integer.")
    if option > 3:
        print("Please enter an integer between 1 and 3.")
    if option >= 1 and option <= 3:
        return option
    else:
        user_input()


def main():
    option = user_input()
    if option == 1:
        print("Option 1 Selected")
    elif option == 2:
        print("Option 2 Selected")
    elif option == 3:
        print("Option 3 Selected")
    else:
        print("Invalid option")


if __name__ == "__main__":
    main()


Asked By: DVuko

||

Answers:

You failed to return the result of the recursive user_input() call, so anytime it recurses, you end up returning None. Using return user_input() instead fixes it, sort of, but it’s a bad solution. Just incorporate the range tests into the existing loop. You get rid of the early break, and just continue any time a condition is invalid, then unconditionally return the value if no tests failed:

def user_input():
    while True:
        try:
            option = int(input("Enter an option: "))
        except ValueError:
            print("Invalid input. Please enter a number between 1 and 3.")
            continue    
        if option < 1:
            print("Invalid value. Please enter a non-negative integer.")
            continue    
        if option > 3:
            print("Please enter an integer between 1 and 3.")
            continue
        # No need to test option >= 1 and option <= 3, the prior tests
        # would continue if it wasn't valid
        return option

Alternatively, you can replace a few of those continues with elif or elses, e.g.:

def user_input():
    while True:
        try:
            option = int(input("Enter an option: "))
        except ValueError:
            print("Invalid input. Please enter a number between 1 and 3.")
            continue    # This continue still needed
        # Continues below this line replaced with exclusive tests via elif/else
        if option < 1:
            print("Invalid value. Please enter a non-negative integer.")
        elif option > 3:
            print("Please enter an integer between 1 and 3.")
        else:
            # Still no need to test option >= 1 and option <= 3, the prior tests
            # would exclude running the else if either passed

            return option
Answered By: ShadowRanger
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.