How to take integer input in Python?



How to take integer input in Python?

In this post, We will see how to take integer input in Python. As we know that Python built-in input() function always returns a str(string) class object. So for taking integer input we have to type cast those inputs into integers by using Python built-in int() function.

Let’s see the examples:

Example 1:

# take input from user
input_a = input()
 
# print data type
print(type(input_a))
 
# type cast into integer
input_a = int(input_a)
 
# print data type
print(type(input_a))

Output:

100
<class 'str'>
<class 'int'>

Example 2:

# string input
input_a = input()
 
# print type
print(type(input_a))
 
# integer input
input_b = int(input())
 
# print type
print(type(input_b))

Output:

10
<class 'str'>
20
<class 'int'>

Example 3:

# take multiple inputs in array
input_str_array = input().split()
 
print("array:", input_str_array)
 
# take multiple inputs in array
input_int_array = [ int(x) for x in input().split()]
 
print("array:", input_int_array)

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]

 

Last Updated on October 24, 2021 by admin

Leave a Reply

Your email address will not be published. Required fields are marked *

Recommended Blogs