How to read python input as integers - Real Python (2023)


  • How to get input values ​​as integers in Python
  • Handling invalid inputs
  • Filter input for valid integers
  • Create a utility function to read valid integers
  • Application
  • Next steps

remove ads

If you have ever coded ainteractive text appin python you probably found that you needed a reliable way to prompt the user for integers as input. It's not enough to just display a message and then collect keystrokes. You need to verify that the user input actually represents an integer. If not, your code should respond appropriately, usually by repeating the message.

In this tutorial, you will learn how to create areusable utility functionwill guaranteevalid integer inputof the interactive user. Along the way, you'll learn about Python's tools for taking a string from the console and converting it to an integer.

Whenever you write a program that interacts with the keyboard, you'll need to code defensively to handle invalid input, so you'll also learn the more pythonic way to deal with this situation. With a function that is guaranteed to return only integers, you can handle all errors.

Free download: Click here to download the sample codewhich you will use to get integer inputs from users in Python.

How to get input values ​​as integers in Python

The Python standard library provides a built-in tool that allows you to receive input from the user, calledProhibited()function. Before using this feature, check that you're using Python 3. If you want to know why this is so important, see the collapsible section below:

python version 2Prohibited()the function was not safe because the interpreter would actually do itcarry outthe string returned by the function before the caller had a chance to check it. This allowed a malicious user to inject arbitrary code into the program.

Due to this problem, Python 2 also provided theRaw data()work as a much safer alternative, but there was always the risk that an unsuspecting developer would choose the more obvious optionProhibited().

Python 3 renamedRaw data()DoProhibited()and removed the old risky version.Prohibited(). You'll be using Python 3 in this tutorial, so this bug won't be an issue.

(Video) Reading Input in Python and Converting Keyboard Input

A Python 3,Prohibited()the function returns achainthen you need to convert it towhole. You can read a string, convert it to an integer andprintresults in three lines of code:


>>>number_as_string = Prohibited("Please enter an integer: ")Please enter an integer: 123>>>number_as_integer = And t(number_as_string)>>>print(F"The integer value is{number_as_integer}")The integer value is 123.

When the above code snippet is executed, the interpreter stops atProhibited()function and prompts the user to enter an integer. A blinking cursor appears at the end of the message and the system waits for the user to type any string of characters.

When the user presses a keyGet into, the function returns a string containing the entered characters, without the new line character. As a reminder that the value you received is a string, you named the receiving variablenumber_as_string.

Your next line tries to parsenumber_as_stringas an integer and store the result innumber_as_integer. you useAnd t()class constructor to perform the conversion. At last,print()the function displays the result.

remove ads

Handling invalid inputs

You've probably already noticed that the above code is hopelessly optimistic. Users cannot always be trusted to provide the information you expect. You can help a lot by providing a clear and quick message, but due to confusion, carelessness or spite there will always be users who provide incorrect data. Your program should be prepared to handle any type of text.

HeProhibited()the function can return any text or even an empty string if the user pressesGet intoimmediately after prompting. How can you make sure that your program doesn't try to perform disorder arithmetic when it expects to?And t?

(Video) Representing Integers in Python

It will use Python's own error handling mechanism. By default, integer conversion will return avalue error exceptionif that fails. Try the above code again, but this time notice how it behaves with invalid input:


>>>number_as_string = Prohibited("Please enter an integer: ")Please enter an integer: kohlrabi>>>number_as_integer = And t(number_as_string)Trace (last call, last):Archive", the line1, W.value error:invalid literal for base 10 int(): "rutabaga"

You will notice that this error does not occur on the line where the value is entered, but on the one where you try to convert it using the built-in function.And t(). It's up to you to deal with itvalue errorexception if this happens.

It seems that a little more care is needed to make sure that the program gets good integer values. You'll take care of that next.

Filter input for valid integers

You saw that the python standard libraryProhibited()The function allows the user to type almost anything on the command line. You need to be sure that you can interpret what you have as an integer.

Here you can take one of two approaches:LBYL EAFP Lubricantthat meansLook around you before you jump.IIt is easier to ask for forgiveness than permissionproperly. Basically, in LBYL your goal is to prevent mistakes from happening. EAFP focuses on handling errors once they occur.

In short, LBYL's strategy is to double-check your data before attempting a conversion. EAFP, on the other hand, jumps at it, immediately attempting the conversion, hoping that Python's exception handling will handle any errors.

While LBYL may seem like a more sophisticated approach, it often injects complex error-checking logic and conditional flows into what should be a simple operation. Also, you should check for errors on each entry, even if it is valid.

For integer verification, the EAFP approach results in not only simpler but also faster code. If a valid integer is provided, you won't waste time looking for error conditions. On the other hand, if the string is invalid, Python will generate a built-in function.value errorexception.

In python you handle exceptions in file atry...except block. containerattemptexceptblock within aone secondloop, you can guarantee that only integers will pass through it. This mechanism is sometimes calledloop of retry.

Here is an example of how to write this almost bulletproof code:


(Video) Python user input ⌨️

1>>>number_as_integer = nico2>>>one second number_as_integer Es nico:3... attempt:4... number_as_integer = And t(Prohibited("Please enter an integer: "))5... except value error:6... print("Invalid integer!")7...8>>>print(F"The integer you entered is{number_as_integer}")

nested call toProhibited()internal connection toAnd t(). It doesn't hurt because justAnd t()the function may fail.

Now, if the user's string can be parsed as a valid integer, then that value is assigned tonumber_as_integerbefore the interpreter returns to the start of the loop and tries againone secondcondition: disease. because this state is nowFALSEHOOD, the loop ends and execution continues at line 8 with a valid integer.

However, if the user string is invalid, thenvalue erroris ejected and the interpreter goes directly toexceptbranch where it prints an error message before returning toone secondstatement on line 2. In this casenumber_as_integerit is stillnicothen the loop will be executed again.

The result of this logic is that your code simply refuses to execute until you get a valid integer.

remove ads

Create a utility function to read valid integers

The above code works pretty well, but it's not reusable. If you copy and paste it into some other logic, you'll probably need to adjust the file name.number_as_integervariable and modify the suggestions to adapt them to the new situation. This approach runs the risk of introducing careless errors.

It would be much better to include the code inown solid function. Once successfully tested, you can think of this feature as a kind of black box: a simple, reliable source of user-entered integers for all your projects.

This is how you can do it. Since you can reuse your function in different situations, it will display a configurable message as well as an optional error message:


>>>definition get_integer(track: ul, Error message: ul = „”) -> And t:... one second TRUE:... attempt:... give back And t(Prohibited(track))... except value error:... print(Error message)...

The advantage of having a function likeget_integer()in its arsenal is that it takes care of common errors internally, so the code that calls it can remain simple. After defining a new function in theANSWERAs stated above, this is how you can test it:


(Video) Python Tutorial for Beginners 3: Integers and Floats - Working with Numeric Data

>>>print(get_integer("Please enter an integer: "))Please enter an integer: foobarPlease enter an integer:Please enter an integer: -123-123>>>print(... get_integer(... track="Enter a value for n: ",... Error message="n must be an integer."... )...)Enter a value for n: jabberwockyn must be an integer.Enter a value for n: 3.1415n must be an integer.Enter a value for n: 999999

if you findget_integer()Useful function, you can save it in the import module. Calmabsolute and relative import in pythonis a great ability that can increase code reuse.

For demo purposes, you can save the function exactly as you defined it above in a file Then, to make it available to another module in the same virtual environment and same directory, the following line at the top is, For example:

#test.pyz get_integer matter get_integer

Heget_integer()The function is a very simple example of reusable code. Once you've stored it in a module, you can call it whenever you need a reliable way to get integers from the user.


Now you can accept user feedback with confidence! Even if the user doesn't enter a valid integer at first, you can be sure that they won't input unnecessary data to your program. Your function will doggedly request information until it gets a valid integer. With these concerns in mind, you can focus on the more enjoyable parts of your project.

In this tutorial you learned:

  • Use the python standard libraryProhibited()functionto get a string from the user
  • Convertstring value to integer value
  • handle errorswhen the input string is not a well-formed integer
  • createrobust reusable functionthat you can incorporate into multiple projects

Code reuse is an important topic in software engineering. The best way to create reliable code is to use small, reliable components. Hisget_integer()The function is an example of this.

Free download: Click here to download the sample codewhich you will use to get integer inputs from users in Python.

Next steps

In this tutorial, you covered a specific strategy for validating user input. Now that you understand what basic input validation is in Python, you might be interested in some open source projects that not only solve this problem, but also include more advanced features:

Here is an example of how you can use it.cooked_entry.get_int()as your customget_integer()function:

z cooked_entrance matter get_intage = get_int(track="Enter your age")

If you want more details about Python input and output, you can keep readingBasic String Input, Output, and Formatting in Pythoniofficial documentation. Also, you can find more information about Python's numeric types in the filenumbers in pythonteaching.

Make all your integers correct!

(Video) How to Write a Python Program That Asks the User for 2 Integers and Then Adds Them


1. Convert input into a list of integers in Python
2. Accepting Input With Python and Starting a Rock, Paper, Scissors Game
(Real Python)
3. Defining Python Functions With Default and Optional Arguments
(Real Python)
4. Introduction to Python's len() function
(Real Python)
5. Python Validation: How to Check If a String Is an Integer
(Max O'Didily)
6. How to Take User Input in Python? #3


Top Articles
Latest Posts
Article information

Author: Ouida Strosin DO

Last Updated: 09/01/2023

Views: 6337

Rating: 4.6 / 5 (76 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Ouida Strosin DO

Birthday: 1995-04-27

Address: Suite 927 930 Kilback Radial, Candidaville, TN 87795

Phone: +8561498978366

Job: Legacy Manufacturing Specialist

Hobby: Singing, Mountain biking, Water sports, Water sports, Taxidermy, Polo, Pet

Introduction: My name is Ouida Strosin DO, I am a precious, combative, spotless, modern, spotless, beautiful, precious person who loves writing and wants to share my knowledge and understanding with you.