Skip to content

How to ask for input in python until the user provides valid input?

Python's built-in function input is the most commonly used function to accpet user input. But what if you want to keep asking for user input until they provide valid input? You could write your custom function that does following:

  1. Accepts user input using input
  2. Determine if it's what the program is expecting. If not, throw an error message to the user and go back to step 1.
  3. Process the user input as per your needs.

This functionality is implemented by the Click python package. Let's see how it works!

Input validation using click

Let's first install (or update) click using pip. Run following in your terminal to install click:

$ pip install -U click

prompt function of the click library asks user for input with the provided prompt message. It also accepts type parameter to check the input type validity. Go ahead and open a python interpreter to see how to perform basic validations.

>>> import click
>>> value = click.prompt('Please enter a valid integer', type=int)
Please enter a valid integer: a
Error: 'a' is not a valid integer.
Please enter a valid integer: %
Error: '%' is not a valid integer.
Please enter a valid integer: \
Error: '\\' is not a valid integer.
Please enter a valid integer:  
Error: ' ' is not a valid integer.
Please enter a valid integer: 123
>>> value
123
>>> 

Often, validations in the real world are application specific. For instance, an application that processes human age(cannot be negative). Lets implement a simple ParamType to represent human age.

import click

class HumanAgeParamType(click.ParamType):
    name = "human age"

    def convert(self, user_input, param, ctx):
        try:
            human_age = int(user_input)
        except ValueError: 
            self.fail(f"{user_input} is not a valid age input", param, ctx)
        if human_age < 0:
            self.fail("Age cannot be negative", param, ctx)
        if human_age > 100:
            print("Hello super human!")
        return human_age

human_age = click.prompt("Provide your age", type=HumanAgeParamType())

Custom parameter specific validation goes inside convert. Copy above snippet to python file age_validation.py, and run it:

$ python3 age_validation.py
Provide your age: abc
Error: abc is not a valid age input
Provide your age: -10
Error: Age cannot be negative
Provide your age: 20
$

As we can see, the library takes care of repeatedly asking for input until we get a valid input.

Have any feedback?

If you have any feedback regarding this guide or need a tutorial on any specific topic, please submit this feedback form.