Reputation: 55
Im trying to take in a a set of numbers from the command line prompt and then have the program print back the smallest number, but I keep getting and index error saying that myArray = (sys.argv[1]) is out of range
import sys
from List import *
def main(int,strings):
myArray = (sys.argv[1])
strings = myArray(sys.argv[1:])
numbers = (int,strings)
smallest = numbers[0]
for i in range(1,len(numbers),1):
if(numbers[i] < smallest):
smallest = numbers[i]
print ("The smallest number is", smallest)
main
Upvotes: 0
Views: 68
Reputation: 48725
An IndexError
means you are trying to access an element of a list that doesn't exists. The sys.argv
list contains in element 0 the name of the script, and in the other elements the command line arguments. So, if you call the script with 0 command line arguments, element 1 won't exist.
Here are two ways to handle this:
# Method one: check first:
if len(sys.argv) <= 1:
sys.exit('You need to call this script with at least one argument')
myArray = (sys.argv[1]) # Why did you add the parenthesis?
...
# Method two: go for it and ask questions later
try:
myArray = (sys.argv[1])
...
except IndexError:
sys.exit('You need to call this script with at least one argument')
Upvotes: 1
Reputation: 473813
Don't reinvent the wheel and use argparse module. It's simple and readable:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-l", "--list", nargs='+', type=int)
args = parser.parse_args()
print("The smallest number is %d" % min(args.list))
Here's what on the console:
$ python test.py -l 1 2 3 4 5
The smallest number is 1
$ python test.py --list 1 2 3 4 5
The smallest number is 1
Upvotes: 1