How to take integer inputs until a valid response is found in python

How to take integer inputs until a valid response is found in python:

In this post, we will learn how to get integer inputs continuously until a valid response is found in Python.

How to solve it:

To solve it, we need to use an infinite loop with try-catch blocks. Inside try, the program will read the user given value. If the value is an integer, it will read that value and keep it in a variable. If it is not an integer, it will throw an exception. The program will print one message to the user to enter a different value, as this is not an integer. It will keep running till an integer value is read.

Program:

Below is the complete program:

while True:
    try:
        user_input = int(input("Enter a number: "))
    except ValueError:
        print("Please enter a valid input !!")
        continue
    else:
        break

print("You have entered: {}".format(user_input))

Here,

  • The program uses a while loop that runs for indefinite amount of time. while True will run the loop indefinitely.
  • Inside try, it is trying to read the user input and convert it to an integer. For anything other than an integer, it will throw ValueError and the control will move to the except block. If it is a valid input, it will move to the else block.
  • For any invalid input, it moves to except block, it will ask the user to enter a valid input, and the continue statement will start the while loop from start.
  • For valid inputs, i.e. for integer inputs, it will move the control to else block and the break statement will break from the infinite loop.

Sample output:

If you run this program, it will give output as like below:

Enter a number: hello
Please enter a valid input !!
Enter a number: 12.334
Please enter a valid input !!
Enter a number: 12
You have entered: 12

python take int input until a valid response

You might also like: