Friday 4 December 2015

Python: functions: Keyword arguments

Functions can also be called using keyword arguments, i.e, by using argument names.

def printEmployee(id, firstName, lastName, designation='Engineer'):
         print(id, firstName, lastName, designation)

Above function can be called in following ways.
printEmployee(id=1, lastName='Gurram', firstName='Hari')
printEmployee(lastName='Krishna', firstName='Rama', id=2)
printEmployee(designation='Tech Lead', lastName='Battu', firstName='Gopi', id=3)


test.py
def printEmployee(id, firstName, lastName, designation='Engineer'):
 print(id, firstName, lastName, designation)
 
printEmployee(id=1, lastName='Gurram', firstName='Hari')
printEmployee(lastName='Krishna', firstName='Rama', id=2)
printEmployee(designation='Tech Lead', lastName='Battu', firstName='Gopi', id=3)

$ python3 test.py
1 Hari Gurram Engineer
2 Rama Krishna Engineer
3 Gopi Battu Tech Lead

Note:
a.   Keyword arguments must follow positional arguments.

def printEmployee(id, firstName, lastName, designation='Engineer'):
         print(id, firstName, lastName, designation)
        
printEmployee(1, lastName='Gurram', firstName='Hari', "engineer")

When you tries to compile above file, you will get following error.

$ python3 test.py
  File "test.py", line 4
    printEmployee(1, lastName='Gurram', firstName='Hari', "engineer")
                                                         ^
SyntaxError: positional argument follows keyword argument



Previous                                                 Next                                                 Home

No comments:

Post a Comment