[Tutor] run with default value if input not given

Oscar Benjamin oscar.j.benjamin at gmail.com
Mon Oct 29 14:32:19 CET 2012


On 29 October 2012 06:06, Saad Javed <sbjaved at gmail.com> wrote:
> Hi,
>
> #!/usr/bin/env python
>
> import sys
>
> x = 'Saad is a boy'
>
> def main(x):
> a = []
> b = x.split(' ')
> for item in b:
> a.append(item)
> print a
> if __name__ == '__main__':
> x = sys.argv[1]
> main(x)
>
>
> How can I make this program run with the default value of x if I don't
> specify an argument at the command line?

My preference is to use Python's default function argument mechanism
to fill in the missing values:

def main(x, y='default'):
    print(x)
    print(y)

if __name__ == "__main__":
    main(sys.argv[1:])

This is the quickest way to get what you want. For a proper script,
though, I would use an argument parser such as argparse.


Oscar


More information about the Tutor mailing list