Friday 4 December 2015

Python: functions: Arbitrary number of arguments

In python, we can define functions that take arbitrary number of arguments. It is similar to varargs in java. ‘*’ is used to represent arbitrary number of arguments.

test.py
def sum(*args):
 i=0
 sum=0
 while (i < len(args)):
  sum+=args[i]
  i+=1
 return sum
 
result1 = sum(10)
result2 = sum(10, 20)
result3 = sum(10, 20, 30)
result4 = sum(10, 20, 30, 40)

print(result1)
print(result2)
print(result3)
print(result4)

$ python3 test.py
10
30
60
100

Arbitrary arguments are stored in a tuple; arbitrary arguments will be last in the list of formal parameters.

Note:

Any arguments that occur after arbitrary arguments must be ‘keyword-only’ arguments.




Previous                                                 Next                                                 Home

No comments:

Post a Comment