Python is a powerful and user-friendly programming language, known for its simplicity and vast capabilities. One area where Python excels is in attaining inputs from users and manipulating them as required. In some circumstances, you may need to take multiple integer inputs in a single line. This article will offer a step-by-step guide on how to achieve that.
Step 1: Using the input() Function
Firstly, Python’s input() function is the built-in function for obtaining user input. The input function returns a string, which we will further convert into integers. See the example below:
1 2 |
num1 = input("Enter a number: ") num2 = input("Enter another number: ") |
In this case, the user needs to enter each number separately. However, if we need to take multiple inputs on the same line, we need to use a different approach.
Step 2: The split() Method
In Python, the string split() method partitions a string into several parts. If the separator is not specified, it separates the string at the spaces. See the example:
1 2 |
numbers = input("Enter two numbers separated by a space: ").split() num1, num2 = numbers |
Here, when two numbers are entered, they are split into separate string elements in a list. However, these are still strings and need to be converted to integers.
Step 3: Converting Strings to Integers
To convert the strings in the list into integers, we use the int() function. It can be combined with a map() function to convert all strings in the list to integers:
1 2 |
numbers = map(int, input("Enter two numbers separated by a space: ").split()) num1, num2 = numbers |
The map() function applies the int() function to each element of the list, converting every string to an integer.
Here is the Full Code
1 2 3 |
numbers = map(int, input("Enter two numbers separated by a space: ").split()) num1, num2 = numbers print(f'First number is {num1} and the second number is {num2}') |
Output
Enter two numbers separated by a space: 10 20 First number is 10 and the second number is 20
Conclusion
In conclusion, taking multiple integer inputs on a single line in Python is simple and straightforward. You just require the use of Python’s input() function, the split() method to separate the inputs, and the map() function to convert the string inputs to integers. It’s part of why Python is such a flexible and powerful language for coding.