Skip to content

Inputting and Converting Python 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. If you’d like to learn why that’s so important, then check out the collapsible section below:

Why you should beware of Python 2’s input() function

Python 2’s version of the input() function was unsafe because the interpreter would actually execute the string returned by the function before the calling program had any opportunity to verify it. This allowed a malicious user to inject arbitrary code into the program. Because of this issue, Python 2 also provided the raw_input() function as a much safer alternative, but there was always the risk that an unsuspecting programmer might choose the more obviously-named input().

Python 3 renamed raw_input() to input() and removed the old, risky version of input(). In this tutorial, you’ll use Python 3, so this pitfall won’t be a concern.

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 rely o