Modules and Functions in Python

Yashi Agarwal
5 min readMay 28, 2020

--

Functions, Modules and Packages

Everyone get confused between all these 3 i.e. Functions, Modules and Packages.

Packages, Modules and Functions

Just see this Image…….We understand that Package contains a collection of modules and a module contains a collection of Functions.

Thus, we can say Functions are the subset of modules and Modules are the subset of Packages.

Modules

A module is simply a Python file with a .py extension that can be imported inside another Python program.

The name of the Python file becomes the module name.

The module contains — 1) definitions and implementation of classes 2) variables and 3) functions that can be used inside another program.

Advantages of modules –

  • Reusability : Working with modules makes the code reusable.
  • Simplicity: Module focuses on a small proportion of the problem, rather than focusing on the entire problem.
  • Scoping: A separate namespace is defined by a module that helps to avoid collisions between identifiers.
Steps In Module

To create a function — A function is defined using the def keyword

1. Creating a Module

Creating Module containing single function

In this program, a function is created with the name “Module” and saving this file with name Yashi.py i.e. name of the file and with extension .py

Creating Module containing many functions

In this program, we have created 4 functions for adding, multiplying, subtracting and division.

Saving this file as Operations.py

2. Importing a Module

Importing a Module

Importing the function using import statement(When interpreter encounters an import statement, it imports the module if the module is present in the search path).

Functions

A function is a block of code which only runs when it is called.You can pass data, known as parameters, into a function.

A function can return data as a result.

Types of Functions

1. User-defined Functions :

Functions that we define ourselves to do certain specific task are referred as user-defined functions.

As u see in above example of Yashi.py file , we created our own function to perform certain operation.

Advantages of user-defined functions

  1. User-defined functions help to decompose a large program into small segments which makes program easy to understand, maintain and debug.
  2. If repeated code occurs in a program. Function can be used to include those codes and execute when needed by calling that function.

2. Built-in Functions :

Python has several functions that are readily available for use. These functions are called 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(),round()

Some built-in functions

abs()returns the absolute value of a number. A negative value’s absolute is that value is positive.

all() returns True if all values in a python iterable have a Boolean value of True otherwise False.

ascii()returns a printable representation of a python object (string or a Python list).

bin() converts an integer to a binary string.

bytearray() returns a python array of a given byte size.

compile() returns a Python code object.

3. Lambda Functions :

They are called as anonymous function that are defined without a name.

While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword.

Use of Lambda Function in python —

To require a nameless function for a short period of time.In Python, we generally use it as an argument to a higher-order function (a function that takes in other functions as arguments).

Lambda functions are used along with built-in functions like filter(), map() etc.

filter() — As the name suggests, it is used to filter the iterables as per the conditions. Filter filters the original iterable and passes the items that returns True for the function provided to filter.

map() — Map executes all the conditions of a function on the items in the iterable and allows you to apply a function on it and then passes it to the output which can have same as well as different values .

Using filter and map function.

As U see in program where we we divide each element with 2 and its modulus equals to 0. The new list which uses filter() returns those number only which are satisfied by the condition while when we use map() returns the elements in boolean form and which are satisfied by the condition returns True.

4. Recursion Functions

A recursive function is a function defined in terms of itself via self-referential expressions. This means that the function will continue to call itself and repeat its behavior until some condition is met to return a result

Syntax

It is an example of a recursive function to find the factorial of an integer.

Factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 3(denoted as 3!) is 1*2*3 = 6.

Here, function ‘factorial’ recursively calls itself till the condition becomes False.

Using Recursive Function

--

--