Only allow Integer user input in Python

avatar

Borislav Hadzhiev

Last updated: Aug 18, 2022

banner

Photo from Unsplash

Only allow Integer user input in Python #

To only allow integer user input:

  1. Use a while True loop to loop until the user enters an integer.
  2. Use the int() class to attempt to convert the value the user entered to an integer.
  3. If the user entered an integer, use the break statement to break out of the loop.
main.py
while True: try: num = int(input('Your favorite integer: ')) print(num) break except ValueError: print('Please enter an integer.')

limit user input to only integers

We used a while True loop to iterate until the user enters an integer value.

The input function takes an optional prompt argument and writes it to standard output without a trailing newline.

The function then reads the line from input, converts it to a string and returns the result.

The input() function always returns a string, even if the user enters an integer.

We used the int() class to try to convert the value the user entered to an integer.

main.py
while True: try: num = int(input('Your favorite integer: ')) print(num) break except ValueError: print('Please enter an integer.')

If the attempt to convert the value fails, a ValueError is raised and the except block runs.

The except block prints the "Please enter an integer" message and the loop re-runs.

If the user enters an integer, we print the integer and break out of the while loop.

The break statement breaks out of the innermost enclosing for or while loop.

If you need to make sure the user enters an integer in a given range, use an if statement.

main.py
while True: try: num = int(input('Integer between 1 and 100: ')) print(num) if num < 1 or num > 100: raise ValueError break except ValueError: print('Please enter an integer between 1 and 100.')

only allow integer user input in range

The code snippet only allows a user to enter an integer between 1 and 100.

If the value is not an integer, is less than 1 or is greater than 100, a ValueError is raised and the loop re-runs.

Once the user enters an integer in the specified range, no ValueError is raised and we break out of the while loop.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.