Python Arbitrary Arguments
Sometimes, we do not know in advance the number of arguments that will be passed into a function. Python allows us to handle this kind of situation through function calls with arbitrary number of arguments.
In the function definition we use an asterisk (*) before the parameter name to denote this kind of argument.
Here is an example.
Example:1
def greet(*names):
"""This function greets all
the person in the names tuple."""
# names is a tuple with arguments
for name in names:
print("Hello",name)
greet("Monica","kapil","Sumit","Jimmy")
Output:
Hello Monica
Hello kapil
Hello Sumit
Hello Jimmy
>>>
Here, we have called the function with multiple arguments. These arguments get wrapped up into a tuple before being passed into the function. Inside the function, we use a for loop to retrieve all the arguments back.
Example:2
Python script to display all the numbers passed as arguments?
Sol:
def cal(*n):
for i in n:
print(i)
#function calling
cal(1,2,3,4)
Output:
1
2
3
4
>>>
Example:3
Python script to display all the numbers passed as arguments, and also calculate and print sum of all the numbers?
Sol:
def cal(*n):
s=0
for i in n:
print(i)
s=s+i
print("Sum = ",s)
#function calling
cal(1,2,3,4)
Output:
1
2
3
4
Sum = 10
>>>
Example:4
Python script to display all the numbers passed as arguments, and also check and print the max no?
Sol:
def cal(*n):
m=0
for i in n:
print(i)
if(i>m):
m=i
print("Max no = ",m)
#function calling
cal(1,12,223,24)
Output:
1
12
223
24
Max no = 223
>>>




