Introduction
In this post, we will explore how to take integer input in Python. The built-in input()
function always returns a string, so we need to convert these inputs into integers using the int()
function.
Examples of Taking Integer Input
Example 1: Basic Integer Input
In this example, we will demonstrate how to take a single integer input and confirm its type.
# Take input from the user input_value = input("Enter a number: ") # Print the data type print("Data type before conversion:", type(input_value)) # Type cast into integer input_value = int(input_value) # Print the data type after conversion print("Data type after conversion:", type(input_value))
Output:
Enter a number: 42 Data type before conversion:Data type after conversion:
Example 2: Taking Multiple Inputs
This example shows how to take multiple integer inputs in an array.
# Take multiple inputs in an array input_array = input("Enter numbers separated by spaces: ").split() print("String array:", input_array) # Convert to integer array int_array = [int(x) for x in input_array] print("Integer array:", int_array)
Output:
Enter numbers separated by spaces: 5 10 15 String array: ['5', '10', '15'] Integer array: [5, 10, 15]
Example 3: Using Map to Store Integers
In this example, we will use the map()
function to convert inputs directly into a list of integers.
# Input size of the list size = int(input("Enter the size of the list: ")) # Store integers in a list using map integer_list = list(map(int, input("Enter the integers (space-separated): ").strip().split()))[:size] print('The list of integers is:', integer_list)
Output:
Enter the size of the list: 3 Enter the integers (space-separated): 4 8 12 16 The list of integers is: [4, 8, 12]
Conclusion
Taking integer input in Python is straightforward using the input()
function followed by type casting with int()
. You can also handle multiple inputs efficiently with techniques like list comprehensions and the map()
function. Properly validating inputs ensures that your program can handle unexpected user input gracefully.
0 Comments