FCBHokie FCBHokie - 6 months ago 33
Python Question

User input integer list

I am trying to create a piece of code that allows me to ask the user to enter 5 numbers at once that will be stored into a list. For instance the code would would be ran and something like this would appear in the shell

Please enter five numbers separated by a single space only:


To which the user could reply like this

1 2 3 4 5


And then the numbers 1 2 3 4 5 would be stored into a list as integer values that could be called on later in the program.

Answer

Your best way of doing this, is probably going to be a list comprehension.

user_input = raw_input("Please enter five numbers separated by a single space only: ")
input_numbers = [int(i) for i in user_input.split(' ') if i.isdigit()]

This will split the user's input at the spaces, and create an integer list.