0% found this document useful (0 votes)
31 views13 pages

Function and Module 22-01-2025 - Jupyter Notebook

The document provides an overview of functions in Python, detailing their purpose, syntax for defining and calling functions, and various examples of function implementations including default arguments, keyword arguments, and lambda functions. It also covers built-in functions like filter() and map(), as well as the concept of recursive functions. The content is structured as a Jupyter Notebook with code snippets demonstrating the concepts discussed.

Uploaded by

nirajjoshi072003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views13 pages

Function and Module 22-01-2025 - Jupyter Notebook

The document provides an overview of functions in Python, detailing their purpose, syntax for defining and calling functions, and various examples of function implementations including default arguments, keyword arguments, and lambda functions. It also covers built-in functions like filter() and map(), as well as the concept of recursive functions. The content is structured as a Jupyter Notebook with code snippets demonstrating the concepts discussed.

Uploaded by

nirajjoshi072003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

1/22/25, 10:58 AM function and module 20-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.

Implementation of the function has two steps:

1. declare the function


2. call the function

Declare/Define the function Syntax: def functionname(parameterlist): <=== function header


statements return

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

return: optional statement, to return the value from the function

Call the function Syntax: functionname(values)

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()

NameError: name 'print_message' is not defined

localhost:8888/notebooks/Desktop/NHANU/python/python jupitor/function and module 20-01-2025.ipynb# 1/13


1/22/25, 10:58 AM function and module 20-01-2025 - Jupyter Notebook

In [ ]: 1 # defining the function


2 ​
3 def print_message():
4 print("hello")
5 print("good Morning")
6 print_message() # no paramenter or no argument

In [ ]: 1 def message(name): # name ha variable ahe


2 print("good morning",name,"Welcome to hell")
3 message("nhanu")

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 # 2ne method of sum


2 ​
3 def add(a,b):
4 print("the addition of given numbers is", a+b)
5
6 add(7,9)

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

localhost:8888/notebooks/Desktop/NHANU/python/python jupitor/function and module 20-01-2025.ipynb# 2/13


1/22/25, 10:58 AM function and module 20-01-2025 - Jupyter Notebook

In [ ]: 1 details("virat",99) # error ala karan marks dile nahi

In [ ]: 1 # defualt argument or default functions(default arguments can be given using


2 ​
3 def details(name,age=18,marks=0):
4 print("name of the student: ",name,"\nage of the student",age,"\nmarks o
5
6 details("rohit")

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

key word argument


solution to above is mentioned parameter _name+value

In [ ]: 1 def details(name,age=18,marks=0): #key word argument


2 print("name of the student: ",name,"\nage of the student",age,"\nmarks o
3
4 details("rohit",marks=92) # hya mule error solve zala

In [ ]: 1 details(32,92,"aparna")

In [ ]: 1 details(age=32,marks=92,name="aparna") # key word argument

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)

localhost:8888/notebooks/Desktop/NHANU/python/python jupitor/function and module 20-01-2025.ipynb# 3/13


1/22/25, 10:58 AM function and module 20-01-2025 - Jupyter Notebook

In [ ]: 1 factorial(2)

In [ ]: 1 factorial (3)

In [ ]: 1 factorial(0)

In [ ]: 1 factorial(-1)

In [ ]: 1 # write a function to check weather the no is prime number or not


2 ​
3 def prime(num):
4 for i in range(2,num):
5 if num%i==0:
6 print("it is not prime no")
7 break
8 else:
9 print(num," it is prime no")
10 break
11 ​

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)

localhost:8888/notebooks/Desktop/NHANU/python/python jupitor/function and module 20-01-2025.ipynb# 4/13


1/22/25, 10:58 AM function and module 20-01-2025 - Jupyter Notebook

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 # write a function to check whether the given no is even or odd:


2 ​
3 def even(num):
4 if num%2==0:
5 print(num,"num is even")
6 else:
7 print(num,"num is odd")

In [ ]: 1 even(7)

In [ ]: 1 even(6)

## Anonymous Function (Lambda function)


A lambda function in Python is like a mini function that you can write in just one line. It's also called
an anonymous function because it doesn’t need a name.

Think of it as a shortcut. Instead of writing a full function using def , you use lambda for simple,
quick tasks.

Syntax of a Lambda Function:

lambda arguments: expression

lambda : This is the keyword that defines a lambda function.


arguments : These are the inputs you want to pass to the function (similar to function
parameters).
expression : This is the calculation or task you want the lambda function to perform. It must
be a single expression (you can’t have multiple lines or return statements).

In [ ]: 1 # write a lambda function for get square:


2 (lambda x:x**2)(5)

In [ ]: 1 (lambda x:x**3)(5) # for a cube

localhost:8888/notebooks/Desktop/NHANU/python/python jupitor/function and module 20-01-2025.ipynb# 5/13


1/22/25, 10:58 AM function and module 20-01-2025 - Jupyter Notebook

In [ ]: 1 sq=(lambda x:x**2)(5)

In [ ]: 1 sq=(lambda x:x**2) # sq madhe variable kel

In [ ]: 1 sq(4)

In [ ]: 1 # user define function for square


2 ​
3 def square(x): # by define function
4 print (x**2)
5 square(10)

In [ ]: 1 # write a lambda function to add two numbers:


2 ​
3 (lambda a,b:a+b)(5,6)

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))

filter(): Filtering Elements from a List


The filter() function is used to filter out elements from an iterable (like a list or tuple) based on
a condition (a function that returns True or False). It creates a new iterable with elements that
satisfy the condition.

Syntax: filter(function, iterable)

function : A function that returns True or False .


iterable : The collection (e.g., list, tuple) you want to filter.

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)

localhost:8888/notebooks/Desktop/NHANU/python/python jupitor/function and module 20-01-2025.ipynb# 6/13


1/22/25, 10:58 AM function and module 20-01-2025 - Jupyter Notebook

In [ ]: 1 list_o=list(filter(lambda x:x%2!=0,num))
2 print(list_o)

In [ ]: 1 # find out age more than 18


2 ​
3 age=[8,18,20,4,3,66,55]
4 election=list(filter(lambda x:x>=18,age))
5 print(election)

map(): Transforming / Changing Elements of a


List
The map() function is used to apply a function to every element in an iterable (like a list or tuple)
and return a new iterable with the transformed values.

Syntax: map(function, iterable)

function : A function that performs some operation on each element.


iterable : The collection (e.g., list, tuple) you want to transform.

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

How Recursion Works:

localhost:8888/notebooks/Desktop/NHANU/python/python jupitor/function and module 20-01-2025.ipynb# 7/13


1/22/25, 10:58 AM function and module 20-01-2025 - Jupyter Notebook

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 # use recursive function to do the same:


2 ​
3 def count(n):
4 print(n)
5 if n==10:
6 pass
7 else:
8 return count(n+1)

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)

NameError: name 're_sum' is not defined

In [4]: 1 # write a recurssive function to find the factorial of number


2 ​
3 def re_fact(n):
4 if n==1:
5 return n
6 else:
7 return n*re_fact(n-1)

In [5]: 1 re_fact(4)

Out[5]: 24

In [7]: 1 re_fact(3)

Out[7]: 6

localhost:8888/notebooks/Desktop/NHANU/python/python jupitor/function and module 20-01-2025.ipynb# 8/13


1/22/25, 10:58 AM function and module 20-01-2025 - Jupyter Notebook

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 [12]: 1 x=50 # global variable

In [14]: 1 def demo():


2 print(x)

In [16]: 1 demo()

50

In [17]: 1 x=20

In [19]: 1 demo()

20

In [21]: 1 def demo():


2 x=15 # the variable which is inside the function is local variab
3 print(x)

In [23]: 1 demo()

15

In [25]: 1 x

Out[25]: 20

In [27]: 1 def demo():


2 global x
3 x=15
4 print(x)

localhost:8888/notebooks/Desktop/NHANU/python/python jupitor/function and module 20-01-2025.ipynb# 9/13


1/22/25, 10:58 AM function and module 20-01-2025 - Jupyter Notebook

In [29]: 1 demo()

15

In [31]: 1 x

Out[31]: 15

Variable length arguments allows a function to accept


unknown number of arguments.

Two types of variable length arguments are there in


Python.

1. *arg

2. **kwarg

In [38]: 1 def demo(*arg):


2 print(type(arg))
3 print(arg)

In [40]: 1 demo(1,2,3,4,5,"s",2)

<class 'tuple'>
(1, 2, 3, 4, 5, 's', 2)

In [41]: 1 # sum of numbers entered by user


2 ​
3 def add(*arg):
4 sum=0
5 for i in arg:
6 sum = sum + i
7 return sum

In [43]: 1 add(1,2,3,4,7)

Out[43]: 17

key word argument


In [44]: 1 # **kwarg
2 def info(**kwarg):
3 print(kwarg.items())

In [46]: 1 info(name="nhanu", age=32, city="mumbai")

dict_items([('name', 'nhanu'), ('age', 32), ('city', 'mumbai')])

localhost:8888/notebooks/Desktop/NHANU/python/python jupitor/function and module 20-01-2025.ipynb# 10/13


1/22/25, 10:58 AM function and module 20-01-2025 - Jupyter Notebook

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")

In [54]: 1 info(name="nhanu", age=32, city="mumbai")

dict_items([('name', 'nhanu'), ('age', 32), ('city', 'mumbai')])


name is a key value and nhanu is a value
age is a key value and 32 is a value
city is a key value and mumbai 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

Using Built-in Modulesreusable code.


In [55]: 1 import math

In [57]: 1 print(dir(math))

['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acos


h', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'co
s', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'fac
torial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isc
lose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log',
'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'pro
d', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trun
c', 'ulp']

In [59]: 1 math.sqrt(9)

Out[59]: 3.0

In [61]: 1 math.factorial(8)

Out[61]: 40320

localhost:8888/notebooks/Desktop/NHANU/python/python jupitor/function and module 20-01-2025.ipynb# 11/13


1/22/25, 10:58 AM function and module 20-01-2025 - Jupyter Notebook

In [63]: 1 math.pi

Out[63]: 3.141592653589793

In [65]: 1 import math as m # m ha alias name dila

In [67]: 1 m.pi

Out[67]: 3.141592653589793

In [69]: 1 m.log(1)

Out[69]: 0.0

In [71]: 1 from math import log, exp

In [73]: 1 log(6)

Out[73]: 1.791759469228055

In [75]: 1 exp(1)

Out[75]: 2.718281828459045

Using User-defined Modules


import modulename

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

from modulename import functioname1, functionname,....

In [76]: 1 import calculator

In [90]: 1 calculator.msg

Out[90]: ' welcome to calculator module'

In [ ]: 1 # he karayacha adhi idle var jaun pahila calculator asa module banvala

In [80]: 1 import calculator as cal

In [82]: 1 cal.add(3,4)

Out[82]: 7

In [84]: 1 cal.div(8,2)

Out[84]: 4.0

localhost:8888/notebooks/Desktop/NHANU/python/python jupitor/function and module 20-01-2025.ipynb# 12/13


1/22/25, 10:58 AM function and module 20-01-2025 - Jupyter Notebook

In [87]: 1 cal.sub(100,6)

Out[87]: 94

In [89]: 1 cal.mul(100,6)

Out[89]: 600

In [ ]: 1 ​

localhost:8888/notebooks/Desktop/NHANU/python/python jupitor/function and module 20-01-2025.ipynb# 13/13

You might also like