How To Take Integer Input In Python 3

In this tutorial, you will learn to take integer input in Python 3.

  • In Python 3, you must use the built-in input() function to accept an integer input.
  • This input() function accepts user input in the form of a string.
  • To determine whether the user input is an integer, use the isdigit() function on it.
  • Then, in order to perform the computations, typecast the string input from the user to an integer value.

Let us take this with some code examples below.

Integer Input In Python 3

Let’s take a look at the code example below, which shows how to use the input() function and the isdigit() function to ensure that the input from the user is an integer.

Suppose you want to add two integer numbers in Python and print the result. Let us see this in the below code example.

#Getting User Input for Numbers
number1 = input("Enter the First Number.")
number2 = input("Enter the Second Number.")

#Check If the input is Number
if(number1.isdigit() and number2.isdigit()):
      #Typecasting number to Integer and Adding Them
      resultSum = int(number1) + int(number2)
      print("The Sum Of Two Number is {}".format(resultSum))
else:
      print("One of the Input is Not Integer")

Output:

Input Example 1:

Enter the First Number.10
Enter the Second Number.20
The Sum Of Two Number is 30

Input Example 2:

Enter the First Number.10.1
Enter the Second Number.20
One of the Input is Not Integer

It is clear from the code that I have taken two inputs from the user, instructing them to enter only integers, and that when I entered a float value, I received the message “Input is not an integer,” as you can see in these input examples.

You can use the isdigit() function to determine whether the input from the user is an integer or not, and then typecast the input to an integer and add it to get the sum.

How To Take Integer Input In Python 3

Wrap Up

I hope you have learned an understanding of how to properly accept integer input from the user in Python 3 and then perform the further computations you require from those numbers.

There are some websites that check to see if the number is an integer after typecasting, but this is incorrect, and you should only typecast the string input to an integer once you have confirmed that the input is an integer, as described above.

If you liked the above tutorial then please follow us on Facebook and Twitter. Let us know the questions and answer you want to cover in this blog.

Further Read:

  1. How To Compare String and Integer in Python
  2. How To Print Fractional Part In Python
  3. [Fix] SyntaxError: unexpected EOF while parsing in Python
  4. Convert All Strings in a List to Int in Python

Leave a Comment