Skip to content Skip to sidebar Skip to footer

Python 3.5.1 - Read Multiple Inputs Into An Array

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 p

Solution 1:

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 1234
[1, 2, 3, 4]

Solution 2:

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 3:

You try to evaluate everything as an int which is obviously not going to work. Try this instead:

data = []

whileTrue:
    entry = input('Item number : ')
    if entry == 'q':
        breaktry:
        data.append(int(entry))
    except:
        print("Not a valid number")

Post a Comment for "Python 3.5.1 - Read Multiple Inputs Into An Array"