Now its time to make some sense.
we are going to create a file named argsFin.py
I user here terminal of linux, if you are a windows user u can do it from cmd or power shell.
import argparse
def fibon(n):
a , b = 0,1
for i in range(int(n)):
a , b = b , a+b
return str(a)
def Main():
argement = argparse.ArgumentParser() #The first step in using the argparse is creating an ArgumentParser object
argement.add_argument('num',help='It will create the \'n\'th finbonacci number ',type = int )
# The first argument is variable name,2nd argement is help message, 3rd argument is variable type
args = argement.parse_args() # passing the argument into args
print('The',str(args.num),'finbonacci number is ',fibon(str(args.num)))
if __name__ == '__main__' : Main()
Here i tell you how the program works.
First we make fibon function.It calculate the Fibonacci number depends on n parameter. The main() function is use for argument passing. First we create a object of argparse module. Then we add 'argement' into that object. The object which is add into 'argement' is have our passed parameter which we give through command line. Then we create an function type variable named args. In args we have the argument now and the variable is 'num'. So we called it by only dot.
Here is the output of the program.
When we need help
root@root:~/Desktop/python/practice# python3.4 argsFin.py --help
usage: argsFin.py [-h] num
positional arguments:
num It will create the 'n'th finbonacci number
optional arguments:
-h, --help show this help message and exit
When we pass valid argument
root@root:~/Desktop/python/practice# python3.4 argsFin.py 6
The 6 Fibonacci number is 8
When we pass wrong argument
root@root:~/Desktop/python/practice# python3.4 argsFin.py ds
usage: argsFin.py [-h] num
argsFin.py: error: argument num: invalid int value: 'ds'
0 Comments