How we set default arguments using Python

Suppose you are writing a python script called code.py. This script accepts different arguments at the command line. The user is able to just supply the first argument and get the default of 5 as the value of b. Or the user is able to supply the first argument and supply the second argument, allowing them to have control over the value b.

import sys

def runCode(a, b = 5):

print a

print b

b = None

a = sys.argv[1]

c = len(sys.argv)

if c > 2:

b = sys.argv[2] runCode(a, b)

else:

runCode(a)

NOTE: the default arguments must always be at the end of the argument list, you can not have a default argument before a real argument in the argument list.

The length of sys.argv is counted starting from 1, 1 being the actual command two being the first argument given. This explains why we say if len(sys.argv) > 2 when we only gave it two arguments. a command with two arguments is a total of 3.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s