0% found this document useful (0 votes)
7 views

7_Functions and Modules

The document provides an overview of functions, modules, and libraries in Python, detailing how to define, create, and call functions, as well as the types of functions available. It explains the concept of modules, how to create and import them, and discusses standard and third-party libraries that enhance Python's functionality. Additionally, it covers specific libraries like math and datetime, and highlights popular libraries for data science, web development, and automation.

Uploaded by

Arif Ahmad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

7_Functions and Modules

The document provides an overview of functions, modules, and libraries in Python, detailing how to define, create, and call functions, as well as the types of functions available. It explains the concept of modules, how to create and import them, and discusses standard and third-party libraries that enhance Python's functionality. Additionally, it covers specific libraries like math and datetime, and highlights popular libraries for data science, web development, and automation.

Uploaded by

Arif Ahmad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Functions, Modules and

Libraries
Learning objective
• What is a Function?
• Rules - Defining a Function
• Creating and calling Functions
• Types of Functions
• What is a Module?
• Creating a Module
• Importing a Module
• Locating Module
• Math Library
• Standard Libraries
• Third Party Libraries
What is a Function?
• A function in Python is a block of reusable code that performs a
specific task.

• It allows you to organize your code into smaller, manageable, and


reusable parts.

• The code inside the function runs when the function is called.
Rules - Defining a Function
• Function blocks begin with the keyword def followed by the
function name and parentheses

• Any input parameters or arguments should be placed within these


parentheses.

• You can also define parameters inside these parentheses.


Rules - Defining a Function
• The code block within every function starts with a colon (:) and is
indented.

• The statement return [expression] exits a function, optionally


passing back an expression to the caller.

• A return statement with no arguments is the same as return None.


Creating a Function
def function_name(parameters):
statement(s)
• Example of Function:

def pow (x, y) :


result = x**y
print(x,"raised to the power", y, "is", result)

• Here, we created a function called pow().


• It takes two arguments, finds the first argument raised to the power of
second argument and prints the result in appropriate format.
Calling a Function
• Defining a function only gives it a name, specifies the parameters
that are to be included in the function and structures the blocks of
code.
• Once a function is defined, you may call by it’s function name with
the required number of arguments/parameters.
• Following is the example to call pow() function:
def pow (x, y) :
result = x**y
print(x,"raised to the power", y, "is", result)

pow(3,2)
Function Example
def sq(a):
return a*a

def cube(a):
return a*a*a

num = int(input("Enter a number: "))


print(sq(num))
print(cube(num))
Types of Functions
• Built-in Functions
• User-defined Functions
• Anonymous/Lambda Functions
Built-in Functions
• Python comes with a set of built-in functions that are always
available, such as print(), len(), type(), int(), and range().

print("Welcome to the world of Python Programming")


length = len("Python")
print(length)
User-defined Functions
• These are functions that you create yourself using the def keyword.
• They encapsulate specific tasks that you can reuse throughout your
code.

def Display():
return 35
D = Display()
print("My age is", D)
Anonymous Functions (Lambda Functions)
• Lambda functions are small, unnamed functions defined using
the lambda keyword.

• They are often used for short, simple operations that are passed
as arguments to other functions.

square = lambda x: x * 2
print(square(5))
What is a Module?
• Module is basically a file in python.

• A module is a file containing Python definitions and statements,


such as functions, classes, or variables, that you can import and
use in other Python scripts.

• Modules help organize and structure code, making it reusable and


easier to maintain.

• Modules are essential for building scalable, maintainable Python


applications by promoting code reusability and modularity.
Creating a Module
• Create a new file in python named as testmodule.py and define 2
functions and one constant variable PI

def greet(name):
return f"Hello, {name}!"

def add(a, b):


return a + b

PI = 3.14159
Importing a Module
• When using a function from a module, use
modulename.functionname
• Create another file in python named as importmodule.py

import testmodule

print(testmodule.greet("Arif"))
print(testmodule.PI)
print(testmodule.add(30,50))
Importing specific functions of variables

from testmodule import PI, add


print(PI)
print(add(50,40))
Import the module with an alias

import testmodule as tm

print(tm.add(40,70))
print(tm.PI)
print(tm.greet("Arif"))
Import all the functions and variables
from testmodule import *
print(add(40,5))
print(PI)
print(greet("Arif Ahmad"))
Locating modules
• The module search path is stored in the system module sys as the
sys.path variable.
• The sys.path variable contains the current directory,
• PYTHONPATH, and the installation-dependent default.
• To find out the current working directory, same as pwd in linux

import os
print(os.getcwd())
Math Library
• The math library is a built-in library in Python that provides
mathematical functions.

import math
print(math.sqrt(4))
print(math.pi)
print(math.floor(2.9))
print(math.ceil(2.9))
The from…import statement
• Python’s from statement lets you import specific attributes from a
library.
• For Example:
from math import sqrt, factorial

• if we simply do "import math", then


• math.sqrt(16) and math.factorial() are needed

print (sqrt(16))
print (factorial(6))
The from…import * statement
• It is also possible to import all names from a module or library into the
current namespace by using the following import statement:
from modulename import *

• This provides an easy way to import all the items from a module into
the current namespace. For Example:
from math import *
print(pow(5,3))
print(radians(30))
print(sqrt(36))
print(degrees(0.5239))
Standard Libraries
• Collection of modules and packages included with Python itself.
• It covers a wide range of functionality, from file I/O and system calls to web
services and data serialization.

• Example modules:
• math: Mathematical functions like sqrt, sin, cos, etc.
• datetime: Date and time manipulation.
• os: Interacting with the operating system, such as reading or writing files.
• json: JSON (JavaScript Object Notation) encoding and decoding.
• re: Regular expressions for string pattern matching.
• collections: Specialized container datatypes like namedtuple, deque, and
Counter.
Import datetime
import datetime
now = datetime.datetime.now()
print(now)
print(now.strftime("%Y-%m-%d %H:%M:%S"))
print(now.time())
print(datetime.date.today())
print(datetime.date.ctime(now))
Python Libraries
Libraries in Python
• Collection of modules and packages that provide pre-written code
to perform common tasks, so you don't have to write everything
from scratch.

• Libraries can contain functions, classes, and variables that you


can use in your own programs.

• Python's extensive standard library and the availability of third-


party libraries make it a powerful language for many types of
applications.
Python Library – Introduction
• Collection of modules and packages that provide pre-written code
to perform common tasks, so you don't have to write everything
from scratch.

• Libraries can contain functions, classes, and variables that you


can use in your own programs.

• In Python standard library and the availability of third-party


libraries make it a powerful language for many types of
applications.
Standard Library
• Collection of modules and packages included with Python itself. It
covers a wide range of functionality, from file I/O and system calls to
web services and data serialization.
• math: Mathematical functions like sqrt, sin, cos, etc.
• datetime: Date and time manipulation.
• os: Interacting with the operating system, such as reading or writing files.
• json: JSON (JavaScript Object Notation) encoding and decoding.
• re: Regular expressions for string pattern matching.
• collections: Specialized container datatypes like named tuple, deque, and
Counter.
Example: math and datetime library
import math
print(math.ceil(5.87))
print(math.sqrt(4))
print("--------------------")

import datetime
now = datetime.datetime.now()
print(now)
print(now.strftime("%Y-%m-%d %H:%M:%S"))
print(now.time())
print(datetime.date.today())
print(datetime.date.ctime(now))
Third-party libraries
• Created by the Python community and are not included in the
standard library.
• You can install these libraries using the pip package manager.
• python installer package similar to rpm in linux / msi in Windows

• (base) C:\Users\admin>pip --version


• (base) C:\Users\admin>pip install numpy
• (base) C:\Users\admin>pip install pandas
• (base) C:\Users\admin>pip list
Example: Third-party libraries
• NumPy:
• Provides support for large, multi-dimensional arrays and matrices, along with a collection of
mathematical functions to operate on these arrays.
• Pandas:
• Offers data structures and tools for data analysis and manipulation, especially useful for handling
tabular data.
• Matplotlib:
• A plotting library for creating static, animated, and interactive visualizations in Python.
• Requests:
• Simplifies HTTP requests, making it easy to interact with web APIs.
• Flask:
• A lightweight web framework for building web applications.
• Django:
• A high-level web framework that encourages rapid development and clean, pragmatic design.
• Scikit-learn:
• A library for machine learning, providing simple and efficient tools for data mining and data
analysis.
Popular Python Libraries by Category
Data Science and ML Web Development:
• NumPy: Numerical
computing. • Django: High-level web
framework.
• Pandas: Data manipulation.
• Flask: Lightweight web
• Matplotlib and Seaborn: framework.
Data visualization.
• Requests: HTTP
• Scikit-learn: Machine requests.
learning.
• BeautifulSoup: Web
• TensorFlow and PyTorch: scraping.
Deep learning.
Popular Python Libraries by Category

Automation and Scripting: Networking:


• Paramiko: SSH and SFTP.
• Selenium: Browser automation.
• BeautifulSoup: Web scraping. • Socket: Low-level networking.
• PyAutoGUI: GUI automation.
Image Processing:
Game Development:
+ Pillow: Image processing.
+ Pygame: Game development
framework. + OpenCV: Computer vision.
+ Panda3D: 3D game engine.
You must have Learnt:
• What is a Function?
• Rules - Defining a Function
• Creating and calling Functions
• Types of Functions
• What is a Module?
• Creating a Module
• Importing a Module
• Locating Module
• Math Library
• Standard Libraries
• Third Party Libraries

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy