0% found this document useful (0 votes)
2 views19 pages

FPP Unit 6 Function Module

The document provides an overview of functions in Python, including built-in, user-defined, and lambda functions, as well as recursion and various argument types. It explains how to declare, call, and utilize functions, along with the concept of modules and packages for organizing code. Additionally, it highlights the importance of the Python Standard Library and mentions several commonly used libraries like TensorFlow, Matplotlib, Pandas, and Numpy.

Uploaded by

tirthu0426
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)
2 views19 pages

FPP Unit 6 Function Module

The document provides an overview of functions in Python, including built-in, user-defined, and lambda functions, as well as recursion and various argument types. It explains how to declare, call, and utilize functions, along with the concept of modules and packages for organizing code. Additionally, it highlights the importance of the Python Standard Library and mentions several commonly used libraries like TensorFlow, Matplotlib, Pandas, and Numpy.

Uploaded by

tirthu0426
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

Zeal Education Society’s

ZEAL COLLEGE OF ENGINEERING & RESEARCH, PUNE – 41


(An Autonomous Institute Affiliated to Savitribai Phule Pune University)
NAAC Accredited with A+ Grade / ISO 21001:2018

DEPARTMENT OF AIML ENGINEERING

Function:

A function is a self-contained, reusable block of code designed to perform a specific,


single task.

Types of Functions in Python

Below are the different types of functions in Python:

● Built-in library function: These are Standard functions in Python

that are available to use.

Eg. - print(), len(), type(), range(), sum(), max(), etc.

● User-defined function: We can create our own functions based on

our requirements.

Python Function Declaration


The syntax to declare a function is:
Zeal Education Society’s
ZEAL COLLEGE OF ENGINEERING & RESEARCH, PUNE – 41
(An Autonomous Institute Affiliated to Savitribai Phule Pune University)
NAAC Accredited with A+ Grade / ISO 21001:2018

DEPARTMENT OF AIML ENGINEERING

Return Statement in Python Function


The function return statement is used to exit from a function and go back
to the function caller and return the specified value or data item to the
caller. The syntax for the return statement is:

return [expression_list]

The return statement can consist of a variable, an expression, or a


constant which is returned at the end of the function execution. If none of
the above is present with the return statement a None object is returned.

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. By the
following example, we can understand how to write a function in Python.
In this way we can create Python function definition by using def keyword.
# A simple Python function
def fun():
print("Welcome to GFG")

Calling a Function in Python

After creating a function in Python we can call it by using the name of the
functions Python followed by parenthesis containing parameters of that
particular function. Below is the example for calling def function Python.
# A simple Python function
def fun():
print("Welcome to GFG")
Zeal Education Society’s
ZEAL COLLEGE OF ENGINEERING & RESEARCH, PUNE – 41
(An Autonomous Institute Affiliated to Savitribai Phule Pune University)
NAAC Accredited with A+ Grade / ISO 21001:2018

DEPARTMENT OF AIML ENGINEERING

# Driver code to call a function


fun()

Python Lambda Function Syntax(anonymous function)

Syntax:
lambda arguments : expression

● lambda: The keyword to define the function.

● arguments: A comma-separated list of input parameters (like in a

regular function).

● expression: A single expression that is evaluated and returned.

Ex-
add = lambda x, y: x + y
print(add(3, 4)) # Output: 7

numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)

numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)

from functools import reduce

numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product)
Zeal Education Society’s
ZEAL COLLEGE OF ENGINEERING & RESEARCH, PUNE – 41
(An Autonomous Institute Affiliated to Savitribai Phule Pune University)
NAAC Accredited with A+ Grade / ISO 21001:2018

DEPARTMENT OF AIML ENGINEERING

Recursive Functions in Python


Recursion in Python refers to when a function calls itself. There are many
instances when you have to build a recursive function to solve
Mathematical and Recursive Problems.

Using a recursive function should be done with caution, as a recursive


function can become like a non-terminating loop. It is better to check your
exit statement while creating a recursive function.

def factorial(n):

result = 1

for i in range(1, n + 1):

result *= i

return result

num = int(input('Enter a number '))

print(factorial(num))

def factorial(n):

if n == 0:

return fi

else:

return n * factorial(n - fi)

print(factorial(4)) # output 24
Zeal Education Society’s
ZEAL COLLEGE OF ENGINEERING & RESEARCH, PUNE – 41
(An Autonomous Institute Affiliated to Savitribai Phule Pune University)
NAAC Accredited with A+ Grade / ISO 21001:2018

DEPARTMENT OF AIML ENGINEERING

Python Function Arguments

Python provides various argument types to pass values to functions,


making them more flexible and reusable. Understanding these types can
simplify your code and improve readability. we have the following function
argument types in Python:

● Default argument

● Keyword arguments (named arguments)

● Positional arguments

● Arbitrary arguments (variable-length arguments *args and

**kwargs)

● Lambda Function Arguments

Default Arguments
Default Arguments is a parameter that have a predefined value if no value
is passed during the function call. This following example illustrates
Default arguments to write functions in Python.

def calculate_area(length, width=5):


area = length * width
print(f"Area of rectangle: {area}")
# Driver code (We call calculate_area() with only
# the length argument)
calculate_area(fi0)
# We can also pass a custom width
calculate_area(fi0, 8)
Zeal Education Society’s
ZEAL COLLEGE OF ENGINEERING & RESEARCH, PUNE – 41
(An Autonomous Institute Affiliated to Savitribai Phule Pune University)
NAAC Accredited with A+ Grade / ISO 21001:2018

DEPARTMENT OF AIML ENGINEERING

Keyword arguments
Keyword arguments are passed by naming the parameters when calling
the function. This lets us provide the arguments in any order, making the
code more readable and flexible.

def fun(name, course):


print(name,course)
# Positional arguments
fun(course="DSA",name="gfg")
fun(name="gfg",course="DSA")

Positional arguments
Positional arguments in Python are values that we pass to a function in a
specific order. The order in which we pass the arguments matters.

This following example illustrates Positional arguments to write functions


in Python.

def productInfo(product, price):


print("Product:", product)
print("Price: 3", price)
# Correct order of arguments
print("Case-fi:")
productInfo("Laptop", fi200)
# Incorrect order of arguments
print("\nCase-2:")
productInfo(fi200, "Laptop")
Zeal Education Society’s
ZEAL COLLEGE OF ENGINEERING & RESEARCH, PUNE – 41
(An Autonomous Institute Affiliated to Savitribai Phule Pune University)
NAAC Accredited with A+ Grade / ISO 21001:2018

DEPARTMENT OF AIML ENGINEERING

Arbitrary arguments (variable-length arguments *args


and **kwargs)
In Python Arbitrary arguments allow us to pass a number of arguments to
a function. This is useful when we don't know in advance how many
arguments we will need to pass. There are two types of arbitrary
arguments:

● *args in Python (Non-Keyword Arguments): Collects extra

positional arguments passed to a function into a tuple.

● **kwargs in Python (Keyword Arguments): Collects extra

keyword arguments passed to a function into a dictionary.

# *args example
def fun(*args):
return sum(args)
Zeal Education Society’s
ZEAL COLLEGE OF ENGINEERING & RESEARCH, PUNE – 41
(An Autonomous Institute Affiliated to Savitribai Phule Pune University)
NAAC Accredited with A+ Grade / ISO 21001:2018

DEPARTMENT OF AIML ENGINEERING

print(fun(fi, 2, 3, 4))
print(fun(5, fi0, fi5))

# **kwargs example
def fun(**kwargs):
for k, val in [Link]():
print(k, val)

fun(a=fi, b=2, c=3)

Using Both
def fun(*args, **kwargs):
print("Positional arguments:", args)
print("Keyword arguments:", kwargs)

fun(fi, 2, 3, a=4, b=5)

Scope:
It is a region of the program where a variable can be accessed. In other
words, scope determines the accessibility/visibility of a variable.
● Global scope: Variables declared outside of all functions are known

as global variables and in the global scope. Global variables are

accessible anywhere in the program.

● Function scope: Variables that are declared inside a function are

called local variables and in the function scope. Local variables are

accessible anywhere inside the function.


Zeal Education Society’s
ZEAL COLLEGE OF ENGINEERING & RESEARCH, PUNE – 41
(An Autonomous Institute Affiliated to Savitribai Phule Pune University)
NAAC Accredited with A+ Grade / ISO 21001:2018

DEPARTMENT OF AIML ENGINEERING

● Block scope: Variable that is declared inside a specific block & can’t

be accessed outside of that block. In order to access the variables of

that specific block, we need to create an object for it.

Module:

A module in Python is simply a file containing Python code. It can define

functions, classes, and variables, and it can also include runnable code.

Modules help you:

● Organize code into smaller, manageable pieces.

● Reuse code across different programs.

● Share functionality across multiple projects.

Create a Python Module


To create a Python module, write the desired code and save that in a file

with .py extension. Let’s understand it better with an example:

Example:

Let’s create a simple [Link] in which we define two functions, one add

and another subtract.


Zeal Education Society’s
ZEAL COLLEGE OF ENGINEERING & RESEARCH, PUNE – 41
(An Autonomous Institute Affiliated to Savitribai Phule Pune University)
NAAC Accredited with A+ Grade / ISO 21001:2018

DEPARTMENT OF AIML ENGINEERING

# A simple module, [Link]

def add(x, y):

return (x+y)

Syntax to Import Module in Python

import module

# importing module [Link]

import calc

print([Link](fi0, 2))

Python Import From Module


Python’s from statement lets you import specific attributes from a module

without importing the module as a whole.

Import Specific Attributes from a Python module

Here, we are importing specific sqrt and factorial attributes from the math

module.

# importing sqrt() and factorial from the

# module math
Zeal Education Society’s
ZEAL COLLEGE OF ENGINEERING & RESEARCH, PUNE – 41
(An Autonomous Institute Affiliated to Savitribai Phule Pune University)
NAAC Accredited with A+ Grade / ISO 21001:2018

DEPARTMENT OF AIML ENGINEERING

from math import sqrt, factorial

# if we simply do "import math", then

# [Link](fi6) and [Link]()

# are required.

print(sqrt(fi6))

print(factorial(6))

Import all names

The * symbol used with the import statement is used to import all the

names from a module to a current namespace.

Syntax:

from module_name import *

What does import * do in Python?

The use of * has its advantages and disadvantages. If you know exactly

what you will be needing from the module, it is not recommended to use *,

else do so.

# importing sqrt() and factorial from the


Zeal Education Society’s
ZEAL COLLEGE OF ENGINEERING & RESEARCH, PUNE – 41
(An Autonomous Institute Affiliated to Savitribai Phule Pune University)
NAAC Accredited with A+ Grade / ISO 21001:2018

DEPARTMENT OF AIML ENGINEERING

# module math

from math import *

# if we simply do "import math", then

# [Link](fi6) and [Link]()

# are required.

print(sqrt(fi6))

print(factorial(6))

[Link]

What is a Package?

A package is a way of organizing related modules into a directory

hierarchy. It helps structure large codebases and promotes reusability.

Think of a package as a folder that contains Python modules (files ending

in .py) and possibly sub-packages.


Zeal Education Society’s
ZEAL COLLEGE OF ENGINEERING & RESEARCH, PUNE – 41
(An Autonomous Institute Affiliated to Savitribai Phule Pune University)
NAAC Accredited with A+ Grade / ISO 21001:2018

DEPARTMENT OF AIML ENGINEERING

my_package/

├── init .py

├── [Link]

└── [Link]

● my_package/: The package folder.

● __init__.py: Makes the folder a package (in Python 3.3+, it's

optional, but often included).

● [Link] and [Link]: Regular Python modules.

Using a Package

Once you've created a package, you can import its modules like this:

import my_package.modulefi

my_package.modulefi.some_function()
Zeal Education Society’s
ZEAL COLLEGE OF ENGINEERING & RESEARCH, PUNE – 41
(An Autonomous Institute Affiliated to Savitribai Phule Pune University)
NAAC Accredited with A+ Grade / ISO 21001:2018

DEPARTMENT OF AIML ENGINEERING

OR

from my_package import modulefi

OR

from my_package.modulefi import some_function

some_function()

Sub-Packages

Packages can contain sub-packages, like this:

my_package/

├── init .py

├── [Link]

└── sub_package/
Zeal Education Society’s
ZEAL COLLEGE OF ENGINEERING & RESEARCH, PUNE – 41
(An Autonomous Institute Affiliated to Savitribai Phule Pune University)
NAAC Accredited with A+ Grade / ISO 21001:2018

DEPARTMENT OF AIML ENGINEERING

modulefi.some_function()

├── init .py

└── sub_module.py

You can access them like:

from my_package.sub_package import sub_module

Python standard library

The Python Standard Library contains the exact syntax, semantics, and

tokens of Python. It contains built-in modules that provide access to basic

system functionality like I/O and some other core modules. Most of the

Python Libraries are written in the C programming language. The Python

standard library consists of more than 200 core modules. All these work

together to make Python a high-level programming language. Python

Standard Library plays a very important role. Without it, the programmers

can’t have access to the functionalities of Python. But other than this,

there are several other libraries in Python that make a programmer’s life

easier. Let’s have a look at some of the commonly used libraries:


Zeal Education Society’s
ZEAL COLLEGE OF ENGINEERING & RESEARCH, PUNE – 41
(An Autonomous Institute Affiliated to Savitribai Phule Pune University)
NAAC Accredited with A+ Grade / ISO 21001:2018

DEPARTMENT OF AIML ENGINEERING

1. TensorFlow: This library was developed by Google in collaboration

with the Brain Team. It is an open-source library used for high-level

computations. It is also used in machine learning and deep learning

algorithms. It contains a large number of tensor operations.

Researchers also use this Python library to solve complex

computations in Mathematics and Physics.

2. Matplotlib: This library is responsible for plotting numerical data.

And that’s why it is used in data analysis. It is also an

open-source library and plots high-defined figures like pie charts,

histograms, scatterplots, graphs, etc.

3. Pandas: Pandas are an important library for data scientists. It is an

open-source machine learning library that provides flexible high-

level data structures and a variety of analysis tools. It eases data

analysis, data manipulation, and cleaning of data. Pandas support

operations like Sorting, Re-indexing, Iteration, Concatenation,

Conversion of data, Visualizations, Aggregations, etc.

4. Numpy: The name “Numpy” stands for “Numerical Python”. It is the

commonly used library. It is a popular machine learning library that

supports large matrices and multi-dimensional data. It consists of

in-built mathematical functions for easy computations. Even

libraries like TensorFlow use Numpy internally to perform several


Zeal Education Society’s
ZEAL COLLEGE OF ENGINEERING & RESEARCH, PUNE – 41
(An Autonomous Institute Affiliated to Savitribai Phule Pune University)
NAAC Accredited with A+ Grade / ISO 21001:2018

DEPARTMENT OF AIML ENGINEERING

operations on tensors. Array Interface is one of the key features of

this library.

5. SciPy: The name “SciPy” stands for “Scientific Python”. It is an

open-source library used for high-level scientific computations.

This library is built over an extension of Numpy. It works with

Numpy to handle complex computations. While Numpy allows

sorting and indexing of array data, the numerical data code is

stored in SciPy. It is also widely used by application developers and

engineers.

6. Scrapy: It is an open-source library that is used for extracting

data from websites. It provides very fast web crawling and high-

level screen scraping. It can also be used for data mining and

automated testing of data.

7. Scikit-learn: It is a famous Python library to work with complex data.

Scikit-learn is an open-source library that supports machine learning.

It supports variously supervised and unsupervised algorithms like

linear regression, classification, clustering, etc. This library works in

association with Numpy and SciPy.

8. PyGame: This library provides an easy interface to the Standard

Directmedia Library (SDL) platform-independent graphics, audio,


Zeal Education Society’s
ZEAL COLLEGE OF ENGINEERING & RESEARCH, PUNE – 41
(An Autonomous Institute Affiliated to Savitribai Phule Pune University)
NAAC Accredited with A+ Grade / ISO 21001:2018

DEPARTMENT OF AIML ENGINEERING

9. SciPy: The name “SciPy” stands for “Scientific Python”. It is an

open-source library used for high-level scientific computations.

This library is built over an extension of Numpy. It works with

Numpy to handle complex computations. While Numpy allows

sorting and indexing of array data, the numerical data code is

stored in SciPy. It is also widely used by application developers and

engineers.

10. Scrapy: It is an open-source library that is used for extracting

data from websites. It provides very fast web crawling and high-

level screen scraping. It can also be used for data mining and

automated testing of data.

11. Scikit-learn: It is a famous Python library to work with complex

data. Scikit-learn is an open-source library that supports machine

learning. It supports variously supervised and unsupervised

algorithms like linear regression, classification, clustering, etc. This

library works in association with Numpy and SciPy.

12. PyGame: This library provides an easy interface to the Standard

Directmedia Library (SDL) platform-independent graphics, audio,


Zeal Education Society’s
ZEAL COLLEGE OF ENGINEERING & RESEARCH, PUNE – 41
(An Autonomous Institute Affiliated to Savitribai Phule Pune University)
NAAC Accredited with A+ Grade / ISO 21001:2018

DEPARTMENT OF AIML ENGINEERING

and input libraries. It is used for developing video games using

computer graphics and audio libraries along with Python

programming language.

13. PyTorch: PyTorch is the largest machine learning library that

optimizes tensor computations. It has rich APIs to perform tensor

computations with strong GPU acceleration. It also helps to solve

application issues related to neural networks.

14. PyBrain: The name “PyBrain” stands for Python Based

Reinforcement Learning, Artificial Intelligence, and Neural

Networks library. It is an open-source library built for beginners

in the field of Machine Learning. It provides fast and easy-to-use

algorithms for machine learning tasks. It is so flexible and easily

understandable and that’s why is really helpful for developers

that are new in research fields.

You might also like