Function Parameters
Function Parameters
Syntax:
def function_name(parameters):
‘’’doc_string’’’
body
return value;
Function Parameters
a) Positional Argument
b) Keyword Argument
-> We can use positional argument and keyword argument simultaneouly
but first we have to take positional argument first.
Semantics
def my_func(a,b):
# code here
-> In this context, a and b are called parameters of my_func
-> Also note that a and b are variables, local to my_func
a) Positional argument
-> Most common way of assigning arguments to parameters, via the order
in which they are passed. i.e their position.
-> consider a case where we have 3 arguments, and we want to make one
of them optional.
-> If a positional parameter is defined with a default value every positional
parameter after it must also be given a default value.
Unpacking iterables
-> (1,2,4)
-> What defines a tuple in Python, is not (), but, 1,2,3 is also a tuple
-> The () are used to make the tuple clearer.
-> it creates a tuple in memory the first element of that tuple is a memory
address which is what b is pointing to, and the second element is a which
is the memory address of what a is pointing to, and then it does the
assignment, we looking for the copy of memory addresses.
Extended unpacking
-> We don’t always want to unpack every single item in an iterable.
-> We may, for example, want to unpack the first value, and then unpack
the remaining values into another variable.
L = [1, 2, 3, 4, 5, 6]
we can achieve this using slicing: a = l[0] b=l[1:]
or using simple unpacking a,b = l[0], l[1:] (aka parallel assignment)
-> Apart from cleaner syntax, it also works with any iterable, not just
sequence types.
Usage with ordered types
a, *b = [-10, 5, 2, 100] ==> a= -10, b=[5,2,100]
a, *b = (-10, 5, 2, 100) ==> a= -10, b=[5,2,100]
a, *b = ‘XYZ’ ==> a= X, b=[‘Y’, ‘Z’]
a, b, *c = 1,2,3,4,5
a, b, *c, d = [1,2,3,4,5]
a, *b, c, d = ‘python’
-> The * operator can only be used once in the LHS an unpacking
assignment.
-> But the * operators works, since it works with any iterable.
-> in practice we rarely unpack sets and dictionaries directly in this way.
-> It is useful though in a situation where you might want to create single
collection containing all items of multiple sets, or all the keys og multiple
dictionaries.
Nested unpacking
l = [1,2 [3,4]]
a,b ,c = l
a,b, (c,d) = l
a,*b,(c,d,e) = [1,2,3,’XYZ’]
*args
-> def func1(a, b, *args)
# code
args is a tuple not a list
The * parameter name is arbitary you can make it whatever you want.
-> We can unpack the list first and then pass it to the function.
-> func(*l)