Learn Python Fundamental in 30 Days — Day 12(Function Part 2)

Let’s start with function with default arguments

def test(x,y,a=1,b=2):
return (
x+y)/(a+b)

Output

test(5,10)
5.0

Accepting 0 or more arguments

Sometimes we need to define a function that accept more than one arguments

def more_args(*args):
print("Type of args: " + str(type(args)))
print("Value of args: " + str(args))

Output

more_args(1)
Type of args: <class ‘tuple’>
Value of args: (1,)
more_args(1,2,3)
Type of args: <class ‘tuple’>
Value of args: (1, 2, 3)
more_args()
Type of args: <class ‘tuple’>
Value of args: ()

NOTE

  • more_args is a normal function except an asterisk right before the argument args.
  • Within the function, args is a tuple
  • By convention, tuple argument’s default name is args but it doesn’t have to be

One more example

def print_args(*args):
for
i in args:
print(i)

Output

print_args(“a”,”b”,”c”)
a
b
c

Now let’s try to run the same code by providing keyword arguments

print_args(a=4,b=7)
Traceback (most recent call last):
File “/usr/local/lib/python3.6/site-packages/IPython/core/interactiveshell.py”, line 2881, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File “<ipython-input-12-ef04b7ecffe6>”, line 1, in <module>
print_args(a=4,b=7)
TypeError: print_args() got an unexpected keyword argument ‘a’

Use of kwargs

>>> def print_kwargs(**kwargs):
… for key, value in kwargs.items():
… print(“Value of key: “ + key + “Value of value: “ + value)

Output

>>> print_kwargs(fname=”Pra”, lname=”lakh”)
Value of key: fnameValue of value: Pra
Value of key: lnameValue of value: lakh

NOTE

  • Kwargs is a dictionary
  • Some caveat if we are combining them them args need to be come first

Just to re-enforce what I mentioned earlier

  • args and kwargs are conventional names. It’s just for readability purpose

1. args: is a tuple(same order as passed in)

2. kwargs: is a dictionary, unordered

Argument Unpacking

def test_fun(a,b,c):
print("Value of a: " + str(a) + " " + "Value of b: " + str(b) + " " + "Value of c: " +str(c))

Output

test_fun(1,2,3)
Value of a: 1 Value of b: 2 Value of c: 3

OR we can do it like this

num = (4,5,6)
test_fun(num[0],num[1],num[2])
Value of a: 4 Value of b: 5 Value of c: 6

OR much efficient way

test_fun(*num)
Value of a: 4 Value of b: 5 Value of c: 6

So this end of Day12, In case if you are facing any issue, this is the link to Python Slack channel https://devops-myworld.slack.com Please send me your details * First name * Last name * Email address to devops.everyday.challenge@gmail.com, so that I will add you to this slack channel