hokeyplyr48
hokeyplyr48

Reputation: 95

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.

Upvotes: 2

Views: 3741

Answers (3)

pp_
pp_

Reputation: 3489

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)

Upvotes: 3

Harald Nordgren
Harald Nordgren

Reputation: 12381

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")

Upvotes: 1

Steven Morad
Steven Morad

Reputation: 2617

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]

Upvotes: 2

Related Questions