Skip to content

Effortlessly Handle Integer Input in Python

[

How to Read Python Input as Integers

by Charles de Villiers Mar 27, 2023 4 Comments basics

If you’ve ever coded an interactive text-based application in Python, then you’ve probably found that you need a reliable way of asking the user for integers as input. It’s not enough simply to display a prompt and then gather keystrokes. You must check that the user’s input really represents an integer. If it doesn’t, then your code must react appropriately—typically by repeating the prompt.

In this tutorial, you’ll learn how to create a reusable utility function that’ll guarantee valid integer inputs from an interactive user. Along the way, you’ll learn about Python’s tools for getting a string from the console and converting that string into an integer.

Whenever you’re writing a program that interacts with the keyboard, you must code defensively to manage invalid inputs, so you’ll also learn the most Pythonic way to deal with this situation. You’ll handle any errors robustly inside a function that’s guaranteed to return nothing but integers.

How to Get Integer Input Values in Python

Python’s standard library provides a built-in tool for getting string input from the user, the input() function. Before you start using this function, double-check that you’re on a version of Python 3.

In Python 3, the input() function returns a string, so you need to convert it to an integer. You can read the string, convert it to an integer, and print the results in three lines of code:

number_as_string = input("Please enter an integer: ")
number_as_integer = int(number_as_string)
print(f"The value of the integer is {number_as_integer}")

When the above snippet of code is executed, the interpreter pauses at the input() function and prompts the user to input an integer. A blinking cursor shows up at the end of the prompt, and the system waits for the user to type an arbitrary string of characters.

When the user presses the Enter key, the function returns a string containing the characters as typed, without a newline. As a reminder that the received value is a string, you’ve named the receiving variable number_as_string.

Your next line attempts to parse number_as_string as an integer and store the result in number_as_integer. You use the int() class constructor to perform the conversion. Finally, the print() function displays the result.

Dealing With Invalid Input

You’ve probably already noticed that the above code is hopelessly optimistic. You can’t always trust that the user will enter a valid integer. They might accidentally type a letter or other non-numeric character.

To handle this situation and make your code robust, you’ll wrap the int() conversion in a try-except block. This allows you to catch any ValueError that occurs if the conversion fails. Inside the block, you can display an error message and repeat the prompt until the user enters a valid integer.

Here’s an updated version of the previous code that incorporates error handling:

while True:
try:
number_as_string = input("Please enter an integer: ")
number_as_integer = int(number_as_string)
break
except ValueError:
print("Invalid input. Please try again.")
print(f"The value of the integer is {number_as_integer}")

With this updated code, the program enters an indefinite loop, which will only break when a valid integer is entered. Inside the loop, the try block attempts the conversion as before. If an error occurs (i.e., the user enters an invalid input), the except block is executed. In this case, an error message is printed, and the loop starts again.

This way, you can ensure that the program will keep asking for a valid integer until the user provides one.

Filtering Your Input for Valid Integers

The previous code works well if the only invalid input is a non-integer. However, what if you also want to filter out negative integers or enforce a specific range of values?

You can add additional logic to the try block to check for these conditions and handle them accordingly. Here’s an example that only accepts positive integers between 1 and 100:

while True:
try:
number_as_string = input("Please enter a positive integer between 1 and 100: ")
number_as_integer = int(number_as_string)
if number_as_integer < 1 or number_as_integer > 100:
raise ValueError
break
except ValueError:
print("Invalid input. Please try again.")
print(f"The value of the integer is {number_as_integer}")

In this modified code, an additional if statement is added inside the try block. It checks whether the number_as_integer falls outside the desired range and raises a ValueError if it does. The except block will then handle this error and repeat the prompt.

By adding more conditions to the if statement, you can further filter the user’s input to fit your desired criteria.

Creating a Utility Function to Read Valid Integers

The previous code snippets work well for a single instance of getting an integer from the user. However, if you need to get multiple integers throughout your program, it can be tedious to repeat the error handling logic each time.

To make your code cleaner and more reusable, you can wrap the input functionality in a utility function. This function will take care of prompting the user, handling errors, and returning a valid integer.

Here’s an example of a utility function that reads a valid positive integer:

def read_positive_integer(prompt):
while True:
try:
number_as_string = input(prompt)
number_as_integer = int(number_as_string)
if number_as_integer < 1:
raise ValueError
break
except ValueError:
print("Invalid input. Please try again.")
return number_as_integer

By encapsulating the input logic inside a function, you can simply call read_positive_integer() whenever you need to get a positive integer from the user. The function will handle all the error checking for you.

Here’s an example of how you can use the utility function in your code:

age = read_positive_integer("Please enter your age: ")
print(f"You are {age} years old.")

With this utility function, you can easily get valid integers from the user without worrying about error handling every time.

Conclusion

Getting integer input from the user in Python requires some defensive coding to handle invalid inputs appropriately. By using the input() function and the int() conversion, you can get a string input and convert it to an integer.

To handle invalid inputs, you can use a try-except block to catch any ValueError and prompt the user to enter a valid integer. You can also add additional conditions to filter the input as needed.

For cleaner and more reusable code, you can create a utility function that encapsulates the input logic and handles all the error checking for you. This allows you to easily get valid integers from the user throughout your program.

Now that you know how to read Python input as integers, you can confidently create interactive text-based applications that rely on user input. Good luck with your coding!