VarArgs parameters

VarArgs Parameters (Variable-Length Arguments)


In some instances you might need to pass more arguments than have already been specified. Going back to the function to redefine it can be a tedious process. Variable-Length arguments can be used instead. These are not specified in the function’s definition and an asterisk (*) is used to define such arguments.

Lets see what happens when we pass more than 3 arguments in the sum() function.

Example:

def sum(x,y,z):
print("sum of three nos :",x+y+z)
sum(5,10,15,20,25)

When the above code is executed, it produces the following result :

TypeError: sum() takes 3 positional arguments but 5 were given

Syntax - Variable-Length Arguments

def function_name(*args):
function_body
return_statement

Example:

def printnos (*nos):
for n in nos:
print(n)
return
# now invoking the printnos() function
print ('Printing two values')
printnos (1,2)
print ('Printing three values')
printnos (10,20,30)

Output:

Printing two values

1

2

Printing three values

10

20

30


CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Sarkari Exam Quiz O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank