Menu
In these tutorials [Part1 & Par2] you will become a pro in python functions. The best way to use this tutorial is to watch the videos and follow along with the code given here. Follow along and feel free to ask your doubts in the comments.
Table of Contents
ToggleA block of code which performs a desired operation is a function. A function is a like a machine, it takes input, does some work and returns output.
def multiply(a, b):
if b%2 == 0:
print(a*b)
else:
print(-1*a*b)
# call the function
output = multiply(2, 4)
print(output)
>>> 8
def add():
pass
def subtract():
pass
In Built Functions are those functions which exists by default in Python. No need to create them, we can use them directly. Below are some examples of in built functions.
len function: To find out the number of elements in a python object.
ls = [1,2,3]
print(len(ls))
>>> 3
dict function: To create an empty dictionary in python.
empty = dict()
print(type(empty))
>>> dict
int function: To convert a string or float object to an integer in python.
int('2')
>>> 2
str function: To convert an integer/float/python object to its string representation.
str(2)
>>> '2'
Functions which we create are user defined functions. They do not exist by default. We have to make them to be able to use them. Below are various types of user defined functions. Below are various types of functions in python.
# simple function
def add(a, b):
val = a+b
print(val)
a = 5
b = 3
add(a,b)
>>> 8
# function with return
def add(a, b):
return a+b
output = add(3,4)
print(output)
>>> 7
# multiple value return
def add_subtract(a, b):
addition = a + b
subtraction = a - b
return addition, subtraction
k = add_subtract(5,2)
print(k)
>>> (7, 3)
# accepting multiple values
addition, subtraction = add_subtract(4,3)
print(addition)
>>> 7
print(subtraction)
>>> 1
The inputs which functions take are called function arguments. In the below example num1 and num2 are two arguments of the function ‘multiply’.
# default arguments
def multiply(num1=5, num2=3):
return num1*num2
print(multiply())
>>> 15
print(multiply(num1=4))
>>> 12
print(multiply(num2=5))
>>> 25
Order of arguments is important.
In the above example, num1 gets the value 5 and num2 gets the value 6.
Assigning values to function arguments is the Keyword Value way of passing arguments.
Order of arguments does not matter.
In the above example num1 gets 5 in both cases and num2 gets 6.
# default arguments
def multiply(num1=5, num2=3):
return num1*num2
Args is a technique to pass unlimited number of arguments to a function in form of positional arguments.
Generally when a function is defined we define the arguments as well but what do we do when we do not know the number of arguments the function can receive. In such cases we use *args to make the function be able to accept any number of inputs.
def total_earnings(name, *args):
print('\nHello ,', name)
for i in args:
print(i*2)
total = sum(args)
print('Your total earning is: ',total)
# call the function
total_earnings('John', 100, 200, 240)
# output
>>>
Hello , John
200
400
480
Your total earning is: 540
# Call the function again with different arguments
total_earnings('Rita', -340, 500, 234, 1000, 500, 320, 420)
# output
>>>
Hello , Rita
-680
1000
468
2000
1000
640
840
Your total earning is: 2634
Kwargs is a technique to pass unlimited number of arguments to a function in form of Keyword arguments.
# write the function with arbritrary number of arguments
def play(name, **kwargs):
print(type(kwargs))
print(kwargs)
# call the function
play('sohan', sohan=17, arshad=24, smita=15, shiva=21)
# output
>>>
<class 'dict'>
{'sohan': 17, 'arshad': 24, 'smita': 15, 'shiva': 21}
# call the function
play('sohan', sohan=17, arshad=24, smita=15, shiva=21, vaibhav=34, vishwottam=3)
# output
>>>
<class 'dict'>
{'sohan': 17, 'arshad': 24, 'smita': 15, 'shiva': 21, 'vaibhav': 34, 'pyprohelp': 3}
Following are all possible return types of a python function. Return types not covered in first 7 are covered in point 8. Please watch the video tutorial for more on this.
1. Integer
2. String
3. List
4. Dictionary
5. Set
6. Tuple
8. Multiple datastructures returned???
7. Function – advanced
8. Class instance
Docstrings tell us about the function, what it takes as input, what it does and what it produces. Docstrings are really helpful to understand any function. We should always write docstrings before writing function code as it will help us be clear and fast while writing the function code. Docstrings provide a faster way to review code without having to read through whole function.
def add(num1, num2):
"""
num1:(int) Input number 1
num2:(int) Input number 2
returns: (int) sum of the given num1 and num2
"""
return a+b
help(add)
# output
>>>
Help on function add in module __main__:
add(num1, num2)
num1:(int) Input number 1
num2:(int) Input number 2
returns: (int) sum of the given num1 and num2
Single line anonymous function.
Uses of lambda functions:
1. for small data manipulations not needed elsewhere
2. Used along with map, filter and reduce.
lambda x : some operation on x
here x is input argument
# example
func = lambda x: x**2
func(2)
>>> 4
# example with multiple inputs
func = lambda x, y: x+y
func(2,3)
>>> 5
func = lambda x: x**2 if x%2 ==0 else x**3
func(3)
>>> 27
func(2)
>>> 4
map function is a in built python function which takes in a function and applies that function to all elements of a given list
Uses: When we need to modify all elements of a list by a similar logic
# example of map function usage
ls = [1,2,3,4,5]
# task: square all the numbers and add 5 to them
new_ls = map(lambda x: x**2 + 5, ls)
print(list(new_ls))
>>> [6, 9, 14, 21, 30]
filter function returns elements from the list for which the lambda function evaluates to True
Uses:
Used to filter out elements from a given python list
# example of filter function
ls = [1,2,3,4,5]
# get only even numbers from the list
evens = list(filter(lambda x: x%2==0, ls))
print(evens)
>>> [2, 4]
To reduce a list into a single value using pairwise iteration.
# example of reduce function
from functools import reduce
ls = [1,2,3,4,5,6]
# min value
reduce(lambda x,y: x if x<y else y, ls)
>>> 1
Function inside a function.
Uses:
def calc(a,b):
def multiply(a,b):
return a*b
def add(a,b):
return a+b
return multiply(a,b)/add(a,b)
calc(5,6)
>>> 2.72
Function inside a function.
Uses:
# inside function scope
def print_val():
val = 2
print(val)
print_val()
>>> 2
# check variable val outside function
val
>>>
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[67], line 1
----> 1 val
NameError: name 'val' is not defined
# variable defined outside
val = 2
def print_val():
print(val)
print_val()
>>> 2
# modify outer value inside function
val = 10
def print_val():
global val
val = 5
print_val()
print(val)
>>> 5
A Function is an object , use del keyword to delete a function just like you would do with any other
python object
def temp():
print('OOOhooooo')
del temp
temp()
>>>
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[35], line 1
----> 1 temp()
NameError: name 'temp' is not defined