Functions and Modules
UNIT II
FUNCTIONS
Python Functions is a block of statements that return the specific task.
The idea is to put some commonly or repeatedly done tasks together and make a
function so that instead of writing the same code again and again for different inputs,
we can do the function calls to reuse code contained in it over and over again.
Some Benefits of Using Functions
Increase Code Readability
Increase Code Reusability
Function Declaration
Types of Functions in Python
There are mainly two types of functions in Python.
Built-in library function: These are Standard functions in Python that are available
to use.
User-defined function: We can create our own functions based on our requirements.
Creating a Function in Python
We can define a function in Python, using the def keyword. We can add any type of
functionalities and properties to it as we require.
def fun():
print("Welcome to CRR")
Calling a Python Function
After creating a function in Python we can call it by using the name of the function followed
by parenthesis containing parameters of that particular function.
def fun():
print("Welcome to CRR")
fun()
Output:
Welcome to CRR
Dept. of Computer Science Page 29
Functions and Modules
Python Function with Parameters
(or)Defining and calling a function with parameters
(or) return statement
Syntax:
def function_name(parameter: data_type) -> return_type:
"""Docstring"""
# body of the function
return expression
Example:
def add(a: int, b: float) -> float:
c=a+b
return c
a,b = 5, 15.2
sum = add(a,b)
print(f"The addition of {a} and {b} results {sum}.")
Output: The addition of 5 and 15.2 results 20.2.
Anonymous Function-LAMDA
Python Lambda Functions are anonymous functions means that the function is without a
name. As we already know the def keyword is used to define a normal function in Python.
Similarly, the lambda keyword is used to define an anonymous function in Python.
Syntax: lambda arguments : expression
This function can have any number of arguments but only one expression, which is
evaluated and returned.
One is free to use lambda functions wherever function objects are required.
You need to keep in your knowledge that lambda functions are syntactically restricted
to a single expression.
It has various uses in particular fields of programming, besides other types of
expressions in functions.
Example:
# Code to demonstrate how we can use a lambda function for adding 4 numbers
add = lambda num: num + 4
print( add(6) )
Output: 10
Dept. of Computer Science Page 30
Functions and Modules
Example 2:
a = lambda x, y : (x * y)
print(a(4, 5))
Output: 20
Recursive Function
The term Recursion can be defined as the process of defining something in terms of itself. In
simple words, it is a process in which a function calls itself directly or indirectly.
Example:
def fact(n):
if n == 1:
return n
else:
return n *fact(n-1)
num = 6
if num < 0:
print("Invalid input ! Please enter a positive number.")
elif num == 0:
print("Factorial of number 0 is 1")
else:
print("Factorial of number", num, "=", fact(num))
Output: Factorial of number 6 = 720
***
Dept. of Computer Science Page 31
Functions and Modules
MODULES
A Python module is a file containing Python definitions and statements.
A module can define functions, classes, and variables.
A module can also include runnable code.
Grouping related code into a module makes the code easier to understand and use.
Name Space
A namespace is a system that has a unique name for each and every object in Python.
An object might be a variable or a method.
Python itself maintains a namespace in the form of a Python dictionary.
Name (which means name, a unique identifier) + Space(which talks something related
to scope). Here, a name might be of any Python method or variable and space depends
upon the location from where is trying to access a variable or a method.
# A simple module, abc.py
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)
Types of namespaces :
When Python interpreter runs solely without any user-defined modules, methods, classes, etc.
Some functions like print(), id() are always present, these are built-in namespaces.
When a user creates a module, a global namespace gets created, later the creation of local
functions creates the local namespace.
The built-in namespace encompasses the global namespace and the global namespace
encompasses the local namespace.
Dept. of Computer Science Page 32
Functions and Modules
The lifetime of a namespace :
A lifetime of a namespace depends upon the scope of objects, if the scope of an object ends,
the lifetime of that namespace comes to an end. Hence, it is not possible to access the inner
namespace’s objects from an outer namespace.
Importing Modules:
We can import the functions, classes defined in a module to another module using the import
statement in some other Python source file.
Syntax: import module
When the interpreter encounters an import statement, it imports the module if the module is
present in the search path. A search path is a list of directories that the interpreter searches for
importing a module.
Example:
# importing module abc.py
import abc
print(abc.add(10, 2))
Importing Module Attributes
Python’s from statement lets you import specific attributes from a module without importing
the module as a whole.
Example: Importing specific attributes from the module
# importing sqrt() and factorial from the module math
from math import sqrt, factorial
# if we simply do "import math", then math.sqrt(16) and math.factorial() are required.
print(sqrt(16))
print(factorial(6))
Import all Names – From import * Statement
The * symbol used with the from import statement is used to import all the names from a
module to a current namespace.
Syntax: from module_name import *
Example: Importing all names
# importing sqrt() and factorial from the module math
from math import *
# if we simply do "import math", then math.sqrt(16) and math.factorial() are required.
print(sqrt(16))
print(factorial(6))
Dept. of Computer Science Page 33
Functions and Modules
Python Module Built-in-Functions(Standard Library Modules)
Python interpreter has a number of built-in functions. They are always available for use in
every interpreter session.
For example print() and input() for I/O, number conversion functions (int(), float(),
complex()), data type conversions (list(), tuple(), set()) etc.
Here is complete list of Python's built-in functions:
abs() delattr() hash() memoryview() set()
all() dict() help() min() setattr()
any() dir() hex() next() slice()
ascii() divmod() id() object() sorted()
bin() enumerate() input() oct() staticmethod()
bool() eval() int() open() str()
breakpoint() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max()
A built-in module may be a Python script (with .py extension) containing useful utilities.
To display list of all available modules, use following command in Python console:
>>>help('modules')
****
Dept. of Computer Science Page 34
Functions and Modules
PACKAGES
A Python module may contain several classes, functions, variables, etc. whereas a Python
package can contains several modules.
In simpler terms a package is folder that contains various modules as files.
Creating Package
Let’s create a package named mypckg that will contain two modules mod1 and mod2. To
create this module follow the below steps –
Create a folder named mypckg.
Inside this folder create an empty Python file i.e. __init__.py
Then create two modules mod1 and mod2 in this folder.
mod1.py
def CRR():
print("Welcome to CRR")
mod2.py
def sum(a, b):
return a+b
The hierarchy of our package looks like this –
mypckg
|
|---__init__.py
|
|
---mod1.py
|
|
---mod2.py
Understanding __init__.py
__init__.py helps the Python interpreter to recognise the folder as package. It also specifies
the resources to be imported from the modules. If the __init__.py is empty this means that all
the functions of the modules will be imported. We can also specify the functions from each
module to be made available.
Dept. of Computer Science Page 35
Functions and Modules
For example, we can also create the __init__.py file for the above module as –
__init__.py
from .mod1 import CRR
from .mod2 import sum
Import Modules from a Package
We can import these modules using the from…import statement and the dot(.) operator.
Syntax:
import package_name.module_name
Example: Import Module from package
We will import the modules from the above created package and will use the functions inside
those modules.
from mypckg import mod1
from mypckg import mod2
mod1.CRR()
res = mod2.sum(10, 20)
print(res)
Output:30
***
Dept. of Computer Science Page 36