Unit - 03(Functions)
Unit - 03(Functions)
Unit - 03(Functions)
Functions:
Function is a block of reusable code that performs a specific task or set
of tasks.
Functions provide a way to organize code into logical and modular
units, making it easier to understand, debug and maintain.
(If a group of statements is repeatedly required then it is not recommended to
write these statements every time separately. We have to define these
statements as a single unit and we can call that unit any number of times
based on our requirement without rewriting. This unit is nothing but
function.)
Types of Functions:
i. Built – in Functions (Pre defined Functions)
ii. User defined Functions
Built – in Functions: The functions which are coming along with Python
software automatically, are called built in functions or pre-defined
functions.
E.g. – id (), type (), print (), input (), eval () etc.
User defined Functions: The functions which are developed by
programmer explicitly according to business requirements, are called user
defined functions.
syntax: (Function definition)
def function_name (parameters):
‘’’doc string ‘’’
…………………….
…………………….
return value
Parameters:
Parameters are inputs to the function. If a function contains parameters, then
at the time of calling, compulsory we should provide values otherwise,
otherwise we will get error.
return statement:
Function can take input values as parameters and executes business logic, and
returns output to the caller with return statement.
E.g.2
def calc (a, b):
sum = a + b
sub = a-b
mul = a*b
div = a/b
return sum, sub, mul, div
t = calc (100, 50)
print (“The results are: “)
for I in t:
print(i)
Types of arguments:
1. positional arguments
2. keyword arguments
3. default arguments
4. variable length arguments
1. positional arguments:
These are the arguments passed to function in correct positional order.
E.g.
def sub (a, b):
print (a-b)
sub (100, 200)
sub (200, 100)
The number of arguments and position of arguments must be matched. If
we change the order then result may be changed.
If we will change the number of arguments then we will get error.
2. keyword arguments:
we can pass argument values by keyword i.e. by parameter name.
E.g.
def wish (name, msg):
print ("Hello", name, msg)
wish (name="Bunny”, msg="Good Morning")
wish (msg="Good Morning", name="Bunny”)
Here the order of arguments is not important but number of arguments must
be matched.
Note: We can use both positional and keyword arguments simultaneously.
But first we have to take positional arguments and then keyword arguments,
otherwise we will get syntax error.
3. default arguments:
Sometimes we can provide default values for our positional arguments.
E.g.
def wish (name = ‘Guest’):
print (‘Hello’, name, ‘Good morning’)
wish (‘Bunny’)
wish ()
If we are not passing any name then only default value will be considered.
***Note:
After default arguments we should not take non default arguments.
def wish (name="Guest", msg="Good Morning"): ===>Valid
def wish (name, msg="Good Morning"): ===>Valid
def wish (name="Guest", msg): ==>Invalid
4. variable length arguments:
Sometimes we can pass variable number of arguments to our function,
such type of arguments is called variable length arguments. We can
declare a variable length argument with * symbol as follows
def f1(*n):
We can call this function by passing any number of arguments including
zero number. Internally all these values represented in the form of tuple.
E.g.
def sum (*n):
total = 0
for n1 in n:
total = total + n1
print (‘The sum = ‘, total)
sum ()
sum (10)
sum (10,20,30,40)
sum (10,20,30,40,50)
Note: After variable length argument, if we are taking any other arguments
then we should provide values as keyword arguments.
Types of Variables
1. Global Variables: The variables which are declared outside of function are
called global variables.
These variables can be accessed in all functions of that module.
E.g.
a = 10 #global variable
def f1 ():
print (a)
def f2 ():
print (a)
f1 () #output-10
f2 () #output-10
2. Local Variables: The variables which are declared inside a function are called
local variables. Local variables are available only for the function in which we
declared it. i.e. from outside of function we cannot access.
E.g.
def f1 ():
a = 10
print (a) #valid
def f2 ():
print (a) #invalid
f1 ()
f2 () #Error: name ‘a’ is not defined
‘global’ keyword:
We can use global keyword for the following 2 purposes:
1. To declare global variable inside function
2. To make global variable available to the function so that we can perform
required modifications.
E.g.
a = 10
def f1 ():
global a
a = 777
print (a)
def f2 ():
print(a)
f1 () #777
f2 () #777
Modules:
Functional Programming:
Example –
# Doubling each element in a list
numbers = [1, 2, 3, 4, 5]
doubled_numbers = map (lambda x: x * 2, numbers)
print(list(doubled_numbers)) # Output: [2, 4, 6, 8, 10]
ii. filter () - Filters elements from an iterable based on a function that returns
True or False, and returns an iterator with the filtered elements.
syntax – filter (function, iterable)
Example –
# Filtering even numbers from a list
numbers = [1, 2, 3, 4, 5]
even_numbers = filter (lambda x: x % 2 == 0, numbers)
print(list(even_numbers)) # Output: [2, 4]
Example –
# Summing up elements in a list
from functools import reduce
numbers = [1, 2, 3, 4, 5]
sum_of_numbers = reduce (lambda x, y: x + y, numbers)
print(sum_of_numbers) # Output: 15
lambda function:
(or)
E.g.-4:
list1 = [40,10,45,33,15,17,56]
div_4 = list (filter (lambda x: (x%4==0), list1))
print(div_4)
List comprehension:
Provides a shorter syntax while creating a new list from the existing list.
syntax –
list_name = [expression for item in iterable if condition == True]
E.g.
names = [‘Aarti’, ‘Aditi’, ‘Aditya’, ‘Ayush’, ‘Dipti’, ‘Charlie’]
a_names = [name for name in names if ‘A’ in name]
print (a_names)
Practice Questions:
01. creating squares of 1 to 10 numbers, using list comprehension
02. filtering even numbers from
list1 = [0,1,2,3,4,5,6,7,8,9]
03. i/p - ['Alice', 'Bob']
o/p - [('Alice',5), ('Bob',3)]
04. i/p – num = [1,2,3,4,5]
o/p – [‘odd’, ‘even’, ‘odd’, ‘even’, ‘odd’]