How can I accept multiple user inputs separated by a space? I don't know the number of inputs, but I do know they are all ints.
Here's some example inputs:
13213 412 8143
12 312
1321 142 9421 9 29 319
I know can do this if I know the number of inputs beforehand, but I'm having trouble making this generic. I could just ask the user to input how many groups of ints he will input:
inputs = int(raw_input("Enter number of raw inputs "))
num = []
for i in xrange(1, inputs):
num.append(raw_input('Enter the %s number: '))
But I am looking for a more elegant solution that doesn't require asking the user 2 questions.
Taking multiple inputs from user in Python. Developer often wants a user to enter multiple values or inputs in one line. In C++/C user can take multiple inputs in one line using scanf but in Python user can take multiple values or inputs in one line by two methods. This function helps in getting a multiple inputs from user .
The Python built-in input () function is used to prompt the user for input and the split () function to split the input with whitespace. 1. Take space-separated input in Python To read a string input from the user in Python, the built-in input () function is used. The input () function always takes input as a string.
Generally, user use a split () method to split a Python string but one can use it in taking multiple input. List comprehension is an elegant way to define and create list in Python.
The Python built-in input () function is used to prompt the user for input and the split () function to split the input with whitespace. 1. Take space-separated input in Python
s = raw_input("Please enter your numbers: ")
mynums = [int(i) for i in s.split()]
# OR
mynums = map(int, s.split())
Try this:
nums = [int(i) for i in raw_input("Enter space separated inputs: ").split()]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With