How to take integer input in Python

Previous
Next

In this tutorial, we will see how to convert list to tuple.

There is difference in how you can take input in python 2.x and 3.x. You need to use raw_input in python 2.x and input in Python 3.x

In Python 3.x, raw_input was renamed to input and the Python 2.x input was removed.

As you might know, raw_input always returns a String object and same is the case with input in Python 3.x

To fix the problem, you need to explicitly make those inputs into integers by putting them in int() function.


Python 3.x example

a = int(input(“Enter a number: “))
b = int(input(“Enter a number: “))

Let’s understand with the help of example.

a = int(input("Enter an Integer: ")) b = int(input("Enter an Integer: ")) print("Sum of a and b:",a + b) print("Multiplication of a and b:",a * b)

Output:

Enter an Integer: 20
Enter an Integer: 10
Sum of a and b: 30
Multiplication of a and b: 200

Python 2.x example

p = int(raw_input(“Enter a number: “))
q = int(raw_input(“Enter a number: “))

Let’s understand with the help of example.

a = int(raw_input("Enter an Integer: ")) b = int(raw_input("Enter an Integer: ")) print("Sum of p and q:",p + q) print("Multiplication of p and q:",p * q)

Output:

Enter an Integer: 20
Enter an Integer: 10
Sum of a and b: 30
Multiplication of a and b: 200

That’s all about How to take integer input in Python.

Previous
Next

Add Comment