Python How To Handle Invalid User Input

In this short article, we will show you a method to handle invalid user input.

To tackle invalid inputs from the user, we can use the while block paired with the try-except blocks that Python provides for us. In this way, we can handle invalid inputs multiple times. Let’s see how.

First, we use the while statement to keep our code in an infinite loop until we get the correct input in this way:

while True:
    num = int(input("Please enter 5: "))
    if num == 5:
        break	
    else:
        print("Error: You did not enter 5.")

We can already see this method will make sure the user enters the correct input. But this can be improved by adding a try-block to handle any error that may arise from the user’s inputs.

For instance, if the user enters a word then the interpreter will raise a ValueError when it tries to convert it to an integer in the input statement.

Hence we include the try-block to handle the error gracefully.

Using the same example from above, here’s how it would look like: 

while True:
    try:
        num = int(input("Please enter 5: "))
        if num == 5:
            break	
        else:
            print("Error: You did not enter 5.")
    except:
        print("Error: please enter only numbers.")

In this way, the program becomes fail-proof and always has an appropriate response for different scenarios;

Entering a number other than 5:

Please enter 5: 10
Error: You did not enter 5.
Please enter 5: 

Entering a non-integer:

Please enter 5: hi
Error: please enter only numbers.
Please enter 5:

Entering 5:

Please enter 5: 5 

Here is a video we made about Exceptions and their place in the programming world. I suggest watching the video if you have trouble understanding whats going on with the try statement and you wish to get a good grasp on exceptions!

With that example, we’ll end this article!

I hope that was helpful!

Here are some other articles that might also help you!

Related Articles

Python: How to handle bad arguments to functions

ValueError: A Step By Step Troubleshooting Guide!

Thanks to Namazi Jamal for his contributions in writing this article!

Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn