Friday, 23 February 2018

command line arguments in python




  • the concept of passing the arguments from command line at the time of running the python program/file,that type of arguments are called command-line arguments.
  • file name also taken as a one of the command line argument.
  • all the command line arguments are stored into list object in the form of strings, that list object stored into the "argv" variable of sys module.

Example:

import sys
print(sys.argv)
print(len(sys.argv))
for p in sys.argv:
    print(p)


Output1:

C:\Desktop>python commandlineargument.py hai siva krishna

['commandlineargument.py', 'hai', 'siva', 'krishna']
4
commandlineargument.py
hai
siva
krishna

Output2:

C:\Desktop>python commandlineargument.py arg1 arg2 arg3

['commandlineargument.py', 'arg1', 'arg2', 'arg3']
4
commandlineargument.py
arg1
arg2
arg3

Example:

import sys
if len(sys.argv)==3:
    try:
        x=int(sys.argv[1])
        y=int(sys.argv[2])
        z=x+y
        print(z)
    except(ValueError):
        print("enter numerical values only")
else:
    print("enter two userdefined arguments only")

Output1:
C:\Desktop>python commandlineargument.py 4 5

9

Output2:
C:\Desktop>python commandlineargument1.py 4

enter two userdefined arguments only

Output3:
C:\Desktop>python commandlineargument1.py 4 abc

enter numerical values only


Thursday, 22 February 2018

reduce function in python

reduce( ) support only python 2.x

reduce( ) doesn't support python 3.x

Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. 

For example, 
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 

calculates ((((1+2)+3)+4)+5). 

The left argument - x is the accumulated value and the right argument - y is the update value from the iterable object.

x=[2,4,5,6,3]
y=reduce(lambda i,j:i+j,x)

print(y)

20