Problem 5.1
Sequence of Numbers
Write a program seq.py
that takes a number n
as argument and prints numbers from 1
to n
. It should support the following two flags.
-s START --start START
print number from START to n instead of 1 to n
-r --reverse
print the numbers in the reverse order
The program should also print approprate help message when used with -h
or --help
flags.
Use the standard library module argparse
for doing this. You may want to checkout the argparse tutorial to know how to use that module.
Expected Output:
$ python seq.py 5
1
2
3
4
5
$ python seq.py -s 3 5
3
4
5
$ python seq.py -r -s 3 5
5
4
3
Solution
import argparse
p = argparse.ArgumentParser()
p.add_argument("n", type=int)
p.add_argument("-s", "--start", type=int, default=1)
p.add_argument("-r", "--reverse", action="store_true", default=False)
args = p.parse_args()
numbers = list(range(args.start, args.n+1))
if args.reverse:
numbers = numbers[::-1]
for n in numbers:
print(n)