0

I've been trying to add two numbers using command line arguments... This is as far as I found on this site about adding 2 numbers using command arguments

import sys
a=sys.argv[1:]
b=sys.argv[2:]
sumn=str(a+b)
print(" sum is",sumn)
2
  • remove the columns when subscripting the sys.argv array, and cats to int Commented Sep 25, 2017 at 9:25
  • 2
    Please take a look at your individual results! For example print out sys.argv[1:] to see what you are doing. You should really learn to understand the code you are copying from elsewhere. Commented Sep 25, 2017 at 9:26

1 Answer 1

3

You need to cast to int and subscript direct values, not slices

import sys
if len(sys.argv) > 2:
    try:
        a = int(sys.argv[1])
        b = int(sys.argv[2])
        print("sum = %d" % (a + b))
    except ValueError:
        print("failed to parse all arguments as integers.")
        exit(1)
else:
    print("Not enough numbers to add")

EDIT: Added error handling as mentioned in the comments

Sign up to request clarification or add additional context in comments.

1 Comment

Maybe you add some code to handle a possible ValueError when the user enters a string that cannot be casted to an integer to make your answer complete.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.