Function and Module 22-01-2025 - Jupyter Notebook
Function and Module 22-01-2025 - Jupyter Notebook
Functions: ¶
Is a group of related statements that perform specific task.
Functions help in breaking our program into smaller chunks, as our program grows larger and
larger, functions will make it more manageable and organized.
Functions also helps in avoiding repetition and make code more reusable. Reusing means calling
the function when it is required.
functionname: uniquely identifiable name for the function. The rules for naming the function is
same as that of the variables
parameterlist: values that will be passed to the function to work on. They are optional. Number of
parameter is user-dependent.
statements: lines of code that will be executed when the function is called. Indent these statements
after the function header
statements written within the function will not be executed automatically, we need to call the
function so that the statements of the function executes
If functions is defined with the parameters then while calling the function we need to pass the
values
In python, the function definitation should be done before the fucntion is called, otherwise the
interpreter will not be able to identify the function name and give an error
In [1]: 1 print_message()
2 print_message()
3 print_message()
4 print_message()
5 print_message()
6 print_message()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [1], in <cell line: 1>()
----> 1 print_message()
2 print_message()
3 print_message()
In [ ]: 1 # take a num from user and add them and return the sum
2
3 def add(a,b):
4 sum=a+b
5 print("the addition of the given number is :", sum )
6
7 add(5,2)
In [ ]: 1 # 3rd method
2
3 def add(a,b):
4 return a+b
5
6 print(add(8,9))
In [ ]: 1 def add(a,b):
2 sum=a+b
3 print("the addition of the given number is :", sum )
4
5 a1=int(input("enter your no:"))
6 b1=int(input("enter your 2nd: "))
7
8 add(a1,b1)
In [ ]: 1 # only by paramenter
2
3 def details(name,age,marks):
4 print("name of student is: ",name,"\nage of the student is : ",age,"\nma
5 # \n use kel next line sathi
6 details("nhanu",22,99.99) # correct positional argument
In [ ]: 1 def details(name,age,marks):
2 print("name of student is: ",name,"\nage of the student is : ",age,"\nma
3 # \n use kel next line sathi
4
5 details(32,"virat",45.55) # by giving wrong syntax is can't done
In [ ]: 1 def details(name,age=18,marks=0):
2 print("name of the student: ",name,"\nage of the student",age,"\nmarks o
3
4 details("rohit",,45) # error ala karan mala direct marks paige hote manun
In [ ]: 1 def details(name,age=18,marks=0):
2 print("name of the student: ",name,"\nage of the student",age,"\nmarks o
3
4 details("rohit",45) # marks 45 entered at age, because the age is 2nd parame
In [ ]: 1 details(32,92,"aparna")
21-01-2025
In [ ]: 1 # let us create a function to find a factorial of a number
2
3 def factorial(num):
4 if num<0:
5 print("input for the factorial is invalid")
6 elif num>0:
7 fact=1
8 for i in range(1,num+1):
9 fact=fact*i
10 print("factorial for",num,"is",fact)
11 else:
12 print("factorial for zero is 1")
In [ ]: 1 factorial(9)
In [ ]: 1 factorial (10)
In [ ]: 1 factorial(2)
In [ ]: 1 factorial (3)
In [ ]: 1 factorial(0)
In [ ]: 1 factorial(-1)
In [ ]: 1 prime(10)
In [ ]: 1 prime(1)
In [ ]: 1 prime(-1)
In [ ]: 1 prime(3)
In [ ]: 1 li=[2,4,5,7,3,8,9,14,18,17]
2
3
4 for num in li:
5 def prime(num):
6 for i in range(2,num):
7 if num==2:
8 print("it is prime")
9 elif num%1==0:
10 print("it is not prime")
11 break
12 elif num%1!=0:
13 print("it is prime no")
14 break
15 else:
16 print(num,"invalid input")
17 break
18 prime(num)
In [ ]: 1 # def prime(num):
2
3 li=[2,4,5,7,3,8,9,14,18,17]
4
5 def prime(num):
6 if num ==2:
7 print(num,"is prime")
8 return
9 for i in range(2,num):
10 if num % i ==0:
11 print(num,"it not prime")
12 return
13 print(num,"is prime")
14
15 for num in li:
16 prime(num)
In [ ]: 1 even(7)
In [ ]: 1 even(6)
Think of it as a shortcut. Instead of writing a full function using def , you use lambda for simple,
quick tasks.
In [ ]: 1 sq=(lambda x:x**2)(5)
In [ ]: 1 sq(4)
In [ ]: 1 add=(lambda a,b:a+b)
2 add(7,8)
In [ ]: 1 (lambda a,b:a*b)
2 multiple=(lambda a,b:a*b)
3 multiple(7,2)
In [ ]: 1 st=lambda s:s.upper()
2 st("nhanu")
In [ ]: 1 (lambda a,b:a/b)
2 div=(lambda a,b:a/b)
3 float(div(7,2))
In [ ]: 1 num=[5,7,22,97,54,62,77,23,73,61]
2 # create a list of only even numbers from the above list
3
4 list_even=list(filter(lambda x:x%2==0,num)
5 print(list_even)
In [ ]: 1 num=[5,7,22,97,54,62,77,23,73,61]
2
3 list_e= list(filter(lambda x:x%2==0,num))
4 print(list_e)
In [ ]: 1 list_o=list(filter(lambda x:x%2!=0,num))
2 print(list_o)
In [ ]: 1 n=[1,2,5,4,7,8]
2
3 cube=list(map(lambda x:x**3,n))
4 print(cube)
In [ ]: 1 animal= ["dog","cat","monkey","fish","elephant",]
2 upper_animal=list(map(lambda x:x.upper(),animal))
3 print(upper_animal)
Recursive Function
A recursive function is a function that calls itself in order to solve a problem. The problem is divided
into smaller, more manageable parts, and the function keeps calling itself until it reaches a base
case (a condition that stops the recursion).
In [ ]: 1 #def demo():
2 print("demo() is calling itself")
3 demo()
In [ ]: 1 #def demo():
2 print("demo() is calling itself")
3 demo()
In [ ]: 1 #demo()
22-01-2025
1. Base Case: The condition where recursion stops. Without it, the function will call itself
infinitely.
2. Recursive Case: The part of the function that calls itself with modified arguments to solve the
smaller part of the problem
In [ ]: 1 # print 0 to 10
2
3 for i in range(0,11):
4 print(i)
In [ ]: 1 count(0)
In [ ]: 1 count(5)
In [ ]: 1 count(8)
In [5]: 1 # write a recurssive function to find sum of "n" number starting from one
2
3 def re_sum(n):
4 if n==1:
5 return n
6 else:
7 return n+re_sum(n+1)
In [1]: 1 re_sum(5)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [1], in <cell line: 1>()
----> 1 re_sum(5)
In [5]: 1 re_fact(4)
Out[5]: 24
In [7]: 1 re_fact(3)
Out[7]: 6
In [10]: 1 re_fact(12)
Out[10]: 479001600
Scope
Now that we have gone over writing our own functions, it's important to understand how Python
deals with the variable names you assign. When you create a variable name in Python the name is
stored in a name-space. Variable names also have a scope, the scope determines the visibility of
that variable name to other parts of your code.
Let's start with a quick thought experiment; imagine the following code:
1. Global Scope Variables: Declared outside of any function or class. They can be accessed and
modified from any part of the code including inside the function
2. Local Scope Variables: Declared inside a function. They are accessiable only within the
function in which they are declare and not outside of it. When the function finishes execution
local variables are discarded.
In [16]: 1 demo()
50
In [17]: 1 x=20
In [19]: 1 demo()
20
In [23]: 1 demo()
15
In [25]: 1 x
Out[25]: 20
In [29]: 1 demo()
15
In [31]: 1 x
Out[31]: 15
1. *arg
2. **kwarg
In [40]: 1 demo(1,2,3,4,5,"s",2)
<class 'tuple'>
(1, 2, 3, 4, 5, 's', 2)
In [43]: 1 add(1,2,3,4,7)
Out[43]: 17
In [52]: 1 # **kwarg
2 def info(**kwarg):
3 print(kwarg.items())
4 for key,values in kwarg.items():
5 print(key,"is a key value and",values,"is a value")
Modules
Need of a Module
Modules in Python are like tools or packages that help you organize your code into smaller,
manageable parts. Without modules, a large program could become difficult to read, maintain, or
troubleshoot. Modules allow you to:
Reuse code: Write functions once and use them in different programs.
Organize code: Break large codebases into smaller, logical parts.
Maintain code: Changes can be made in one module without affecting others.
Avoid repetition: Common tasks can be separated into a module and reused.
What is a Module?
A module is simply a file containing Python code—like functions, variables, or classes—that can be
imported and used in other Python programs. Think of a module as a library of
In [57]: 1 print(dir(math))
In [59]: 1 math.sqrt(9)
Out[59]: 3.0
In [61]: 1 math.factorial(8)
Out[61]: 40320
In [63]: 1 math.pi
Out[63]: 3.141592653589793
In [67]: 1 m.pi
Out[67]: 3.141592653589793
In [69]: 1 m.log(1)
Out[69]: 0.0
In [73]: 1 log(6)
Out[73]: 1.791759469228055
In [75]: 1 exp(1)
Out[75]: 2.718281828459045
modulename.funtionname(parameters)
modulename.variable
import modulename
In both the above imports we are refering or importing the entire module, but whatif we want to
import a particular part of the module
In [90]: 1 calculator.msg
In [ ]: 1 # he karayacha adhi idle var jaun pahila calculator asa module banvala
In [82]: 1 cal.add(3,4)
Out[82]: 7
In [84]: 1 cal.div(8,2)
Out[84]: 4.0
In [87]: 1 cal.sub(100,6)
Out[87]: 94
In [89]: 1 cal.mul(100,6)
Out[89]: 600
In [ ]: 1