Skip to content
Advertisement

Asking the user for input until they give a valid response

I am writing a program that accepts user input.

JavaScript

The program works as expected as long as the the user enters meaningful data.

JavaScript

But it fails if the user enters invalid data:

JavaScript

Instead of crashing, I would like the program to ask for the input again. Like this:

JavaScript

How do I ask for valid input instead of crashing or accepting invalid values (e.g. -1)?

Advertisement

Answer

The simplest way to accomplish this is to put the input method in a while loop. Use continue when you get bad input, and break out of the loop when you’re satisfied.

When Your Input Might Raise an Exception

Use try and except to detect when the user enters data that can’t be parsed.

JavaScript

Implementing Your Own Validation Rules

If you want to reject values that Python can successfully parse, you can add your own validation logic.

JavaScript

Combining Exception Handling and Custom Validation

Both of the above techniques can be combined into one loop.

JavaScript

Encapsulating it All in a Function

If you need to ask your user for a lot of different values, it might be useful to put this code in a function, so you don’t have to retype it every time.

JavaScript

Putting It All Together

You can extend this idea to make a very generic input function:

JavaScript

With usage such as:

JavaScript

Common Pitfalls, and Why you Should Avoid Them

The Redundant Use of Redundant input Statements

This method works but is generally considered poor style:

JavaScript

It might look attractive initially because it’s shorter than the while True method, but it violates the Don’t Repeat Yourself principle of software development. This increases the likelihood of bugs in your system. What if you want to backport to 2.7 by changing input to raw_input, but accidentally change only the first input above? It’s a SyntaxError just waiting to happen.

Recursion Will Blow Your Stack

If you’ve just learned about recursion, you might be tempted to use it in get_non_negative_int so you can dispose of the while loop.

JavaScript

This appears to work fine most of the time, but if the user enters invalid data enough times, the script will terminate with a RuntimeError: maximum recursion depth exceeded. You may think “no fool would make 1000 mistakes in a row”, but you’re underestimating the ingenuity of fools!

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement