'Python 3.5.1 - read multiple integers on the same input line into a list
I'm using python 3.5.1 and running my file through command prompt on windows. The arguments are being passed after the program is run; ie the program prompts for input based on a previously generated list.
I'm looking to read in multiple numbers on the same line separated by spaces. Python 2.X it wouldn't have been an issue with raw_input but this is proving to be a challenge.
selection = list(map(int,input("Enter items to archive (1 2 etc):").split(",")))
If I enter two different numbers on the same line:
Enter items to archive (1 2 etc):29 30 Traceback (most recent call last): File "G:\Learning\Python\need_to_watch.py", line 15, in selection = list(map(int,input("Enter items to archive (1 2 etc):").split(","))) File "", line 1 29 30 ^ SyntaxError: unexpected EOF while parsing
I gave up on a single line and tried just doing it in a loop but I get a different error
data=[]
while True:
entry = int(input('Item number : '))
data.append(entry)
if entry == 'q':
break
It tries to evaluate 'q' as a variable even though I haven't eval()'d anything.
This question says to just use input().split() but it would appear that this no longer works.... accepting multiple user inputs separated by a space in python and append them to a list
I could try and catch the EOF exception, but that doesn't seem like the right way to do it, nor should it be necessary.
Solution 1:[1]
entry = input('Enter items: ')
entry = entry.split()
entry = list(map(int, entry))
print(entry)
Or more concisely:
entry = list(map(int, input('Enter items: ').split()))
print(entry)
Solution 2:[2]
If you want to pass arguments to a python script, you may want to take a look at argparse instead: https://docs.python.org/3/library/argparse.html
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('integers', type=int, nargs='+')
args = parser.parse_args()
print(args.integers)
python script.py 1 2 3 4
[1, 2, 3, 4]
Solution 3:[3]
You try to evaluate everything as an int
which is obviously not going to work. Try this instead:
data = []
while True:
entry = input('Item number : ')
if entry == 'q':
break
try:
data.append(int(entry))
except:
print("Not a valid number")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Wiktor Stribiżew |
Solution 2 | Steven Morad |
Solution 3 | Harald Nordgren |