Not really sure what a command line argument is, but here is an example question that I don't understand:

"Write a program that gets 4 integers as command-line arguments, prints the values and their total."

Can somebody show me how to do this? I have like 10 of these to do, but don't know where to begin.

Command line arguments you can access like normal list, just import sys and then access sys.argv, element 0 is the name of program, usually you process parameter is sys.argv[1:] part.

import sys
print 'Parameters are:'
for item in sys.argv: print item

You run command from command window with parameters:

D:\Python Projects\Tests> 1 2 3 4
Parameters are:
D:\Python Projects\Tests\

Edited 6 Years Ago by pyTony: n/a

Thanks for your response, so would the answer look like this?

import sys
total = 0
for i in sys.argv[1:4]:
    total += sys.argv[i]

print sys.argv[1:],total

Yes, except it would concatenate the strings, instead of adding values. You must transform the aya.argv[1:4] arguments to integers or floats. also you can just leave out the 4 and accept any number of arguments. I do not know if you are required to react to wrong input, no parameters etc.

Nicer to also print like:

print '+'.join(sys.argv[1:],'=',total

Edited 6 Years Ago by pyTony: n/a

How would you make it an int? I've tried eval() and int() but neither of them worked =\

It should work:

import sys
total = 0
for i in sys.argv[1:]:
    total += int(i)

print '+'.join(sys.argv[1:]),'=',total
D:\Tests> 1 2 3 4
1+2+3+4 = 10
This question has already been answered. Start a new discussion instead.