How to Only Allow Integer User Input in Python?

Estimated read time 2 min read

In Python, you can use the input() function to accept user input. To only allow integer user input, you can use a loop that repeatedly prompts the user to enter an integer until a valid input is entered.

Here is an example:

while True:
    try:
        user_input = int(input("Enter an integer: "))
        break
    except ValueError:
        print("Error: Please enter an integer.")

print("You entered:", user_input)

In this example, we use a while loop to repeatedly prompt the user to enter an integer. We use the input() function to accept user input and convert it to an integer using the int() function.

We use a try/except block to catch the ValueError exception that is raised if the user enters a non-integer input. If the input is not an integer, we print an error message and continue the loop. If the input is an integer, we break out of the loop and print the input using the print() function.

Note that this example only works if the user enters a valid integer. If the user enters a non-integer input that can be converted to a float, such as “3.14”, the input will be converted to an integer without raising an exception. If you need to only allow integer inputs and disallow inputs that can be converted to a float, you may need to use a different method to validate the input.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply