In Python, the built-in input() function always returns a string. To take integer input, the string must be typecast into an integer using the int() function. This article demonstrates multiple ways to take integer input in Python with examples.
Example 1: Taking Single Integer Input
a = input()
print(type(a))
a = int(a)
print(type(a))
Output
100
<class 'str'>
<class 'int'>
Explanation:
- input() returns a string by default.
- int(a) converts the input to an integer.
Example 2: Taking Multiple Inputs Separately
a = input()
print(type(a))
b = int(input())
print(type(b))
Output
10
<class 'str'>
20
<class 'int'>
Explanation:
- The first input remains a string.
- The second input is converted to an integer using int()
Example 3: Taking Multiple Integer Inputs in a List
a = input().split()
print("array:", a)
b = [int(x) for x in input().split()]
print("array:", b)
Output
10 20 30 40 50 60 70
array: ['10', '20', '30', '40', '50', '60', '70']
10 20 30 40 50 60 70
array: [10, 20, 30, 40, 50, 60, 70]
Explanation:
- split() separates the input string into a list of strings.
- List comprehension with int(x) converts each element to an integer.
Example 4: Taking Integer Input with List Size
n = int(input("Enter the size of list: "))
lst = list(map(int, input(
"Enter the integer elements of list(Space-Separated): ").strip().split()))[:n]
print('The list is:', lst)
Output
Enter the size of list: 4
Enter the integer elements of list(Space-Separated): 6 3 9 10
The list is: [6, 3, 9, 10]