7

Im trying to make a function that takes from 1 up to 5 arguments and does different calculations depending on the number given. My idea was something like this:

def function(*args)
    num_of_args = (!!here is the problem!!)
if(num_of_args == 1) : result = a
else if(number_of_args == 2) : result = a+b

and so on I have tried to count number of arguments and assign that number to a variable but can't find a way I imagine that there is possibly no need to use 5 if's but I don't realy want to focus on it before I manage to count those arguments

2 Answers2

5

You can use len(args).

def function(*args):
    if len(args) == 0:
        print("Number of args = 0")
    elif len(args) == 1:
        print("Number of args = 1")
    else:
        print("Number of args >= 2")
kdheepak
  • 1,274
  • 11
  • 22
3

with *args, positional argumets are sent as list. You can access them using args[0],args[1].... also the length by len(args)

def foo(*args):
  print(len(args))
Prakash Palnati
  • 3,231
  • 22
  • 35