Tech Notes

Python: Arguments types

def person(name, age): # a,b are called formal arguments
    return name, age-5

person("peth",25) # a,b here are called actual argments

Type 1: Positional arguments

person(“peth”,25)

Type 2: Keyword arguments

person(name=”peth”, age=25)

Type 3: Default

def person(name, age=25):
    return name, age-5

Type 4: Variable length

def sum(a,b):
    return a+b
what if I want to have some of different number of arguments I want to pass. eg: from sum, I want sum of 1,2,3. I also want sum of 3,4,5,68 --> above sum function won't work here.

we can use variable length arguments:
def sum(*a):
   type(a) --> it will be a tuple
   c = 0 
   for i in a:
      c = c + I
   return c

sum(1,2,3)

Type 5: Keyworded Variable Length Arguments

what if we want to pass keyword too while passing the argument:

In [38]: def person(name, **kwargs):
    ...:     print(kwargs)
    ...:
In [40]: person("Tony Stark", age=12, movie="avengers" )
{'age': 12, 'movie': 'avengers'}

Posted

in

by

Tags: