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.

Recommended Answers

All 6 Replies

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>pyparams.py 1 2 3 4
Parameters are:
D:\Python Projects\Tests\pyparams.py
1
2
3
4

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

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>sum.py 1 2 3 4
1+2+3+4 = 10

use the getopt module. It's pretty frigging awesome

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.