Thanks to visit codestin.com
Credit goes to www.scribd.com

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

Module Notes

Uploaded by

vishaks2722
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 views20 pages

Module Notes

Uploaded by

vishaks2722
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/ 20

Moduels and packages:

Basic Import :
Syntax:

import module_name

Example:

import math

print(math.sqrt(16)) # Output: 4.0

2. Import with Alias


Syntax:

pythonCopy code
import module_name as alias

Example:

pythonCopy code
import numpy as np

Moduels and packages: 1


print(np.array([1, 2, 3])) # Output: [1 2 3]

3. Import Specific Functions or Classes


Syntax:

pythonCopy code
from module_name import function_name

Example:

pythonCopy code
from math import sqrt

print(sqrt(16)) # Output: 4.0

4. Import Multiple Functions or Classes


Syntax:

pythonCopy code
from module_name import function1, function2

Example:

pythonCopy code
from math import sqrt, pi

print(sqrt(16)) # Output: 4.0


print(pi) # Output: 3.141592653589793

Moduels and packages: 2


5. Import All Functions or Classes from a Module
Syntax:

pythonCopy code
from module_name import *

Example:

pythonCopy code
from math import *

print(sqrt(16)) # Output: 4.0


print(pi) # Output: 3.141592653589793

Note: Using from module_name import * is generally discouraged as it can make the
code less readable and lead to name conflicts.

6. Import from a Submodule or Package


Syntax:

pythonCopy code
from package_name import module_name

Example:

pythonCopy code
from datetime import datetime

print(datetime.now()) # Output: current date and time

Moduels and packages: 3


The construct if __name__ == "__main__": in Python is a powerful and flexible way to
control the execution of code based on whether a script is being run directly or
imported as a module. Understanding this construct is essential for writing
modular and reusable code. Let’s delve into the details:

What is if __name__ == "__main__": ?


__name__ : This is a special built-in variable in Python. It holds the name of the
module (file) in which it is used. When a script is executed, Python sets the
__name__ variable to "__main__" in that script. When a module is imported into

another script, Python sets __name__ to the module's name.

"__main__" : This is a string that represents the name of the script being run
directly. It indicates that the script is being executed as the main program.

How Does It Work?


When a Python file is executed, the interpreter sets the __name__ variable to
"__main__" in that file. This allows you to differentiate between whether the script is

being run directly or imported as a module.

Here’s how the if __name__ == "__main__": construct works:

1. Direct Execution:
If you run the Python script directly (e.g.,
python myscript.py ), Python sets __name__ to "__main__" . Therefore, the code
inside the if __name__ == "__main__": block will be executed.

Moduels and packages: 4


2. Importing as a Module:
If the script is imported into another script (e.g.,
import myscript ), Python sets __name__ to the name of the module (e.g.,

"myscript" ). As a result, the code inside the if __name__ == "__main__": block will
not be executed.

Why Use if __name__ == "__main__": ?


1. Code Reusability:
This construct allows you to write code that can be reused as a module in
other scripts. Code inside the
block is intended to be run only when the script is
if __name__ == "__main__":

executed directly, not when it is imported.

2. Testing and Debugging:


You can include test code or debugging code in the
if __name__ == "__main__": block. This code will only run when you want to test

or debug the module directly, without affecting the module’s behavior when
imported elsewhere.

3. Organization:
It helps in organizing the script by separating the executable code from the
importable functions or classes. This separation improves code clarity and
structure.

Detailed Example
Let’s illustrate this with examples.

Example 1: Running the Script Directly

script1.py:

pythonCopy code
# script1.py

def hello():
print("Hello from script1!")

if __name__ == "__main__":

Moduels and packages: 5


print("script1 is being run directly.")
hello()

Running script1.py directly:

bashCopy code
python script1.py

Output:

csharpCopy code
script1 is being run directly.
Hello from script1!

In this case, __name__ is set to "__main__" , so the code inside the if __name__ ==

"__main__": block executes.

Example 2: Importing as a Module

script2.py:

pythonCopy code
# script2.py
import script1

print("script2 is running.")
script1.hello()

Running script2.py :

bashCopy code
python script2.py

Moduels and packages: 6


Output:

csharpCopy code
script2 is running.
Hello from script1!

In this case, script1 is imported as a module. The code inside if __name__ ==

"__main__": in script1.py is not executed, so the line "script1 is being run


directly." does not appear.

Summary
if __name__ == "__main__": is used to check if a script is run directly or imported
as a module.

Direct Execution: Code inside the if __name__ == "__main__": block runs when
the script is executed directly.

Importing: Code inside the block does not run when the script is imported into
another script.

Use Cases: It allows for code reusability, testing, debugging, and better
organization.

PyPI (Python Package Index) and pip (Python package installer) are fundamental
tools in the Python ecosystem for managing third-party libraries and packages.
Here’s a detailed explanation of their uses, why they are essential, and practical
examples to illustrate their importance.

Moduels and packages: 7


What is PyPI?
PyPI (Python Package Index) is a repository for Python packages. It allows
developers to publish, share, and find Python libraries and tools. PyPI hosts
thousands of packages that extend Python’s functionality, ranging from simple
utilities to complex frameworks.
Uses of PyPI:

1. Access to Libraries: Provides access to a vast collection of third-party


libraries that can help you avoid reinventing the wheel. For example, you can
find packages for data analysis, web development, machine learning, and
more.

2. Code Sharing: Allows developers to share their code with the community,
promoting collaboration and reuse.

3. Package Discovery: Helps you discover and evaluate packages through


descriptions, documentation, and user ratings.

Example:

Requesting HTTP Data: If you want to fetch data from a web service, you can
use the requests package available on PyPI.

What is pip?
pip is the package installer for Python. It is a command-line tool used to install and
manage Python packages from PyPI. Pip simplifies the process of downloading
and installing packages and their dependencies, ensuring that you can easily
integrate external libraries into your projects.

Uses of pip:

1. Installing Packages: Easily install packages from PyPI into your Python
environment.

2. Managing Dependencies: Handle package dependencies automatically,


making it easier to work with complex libraries.

3. Upgrading and Uninstalling: Update or remove packages as needed.

Example:

Moduels and packages: 8


Installing Requests Package: Use pip to install the requests package from
PyPI.

How PyPI and pip Work Together


1. Finding a Package on PyPI
To use a package, you first need to find it on PyPI. For example, if you need a
package to work with HTTP requests, you might look for requests on PyPI’s
website. You’ll find information about the package, including installation
instructions and usage examples.
2. Installing a Package with pip

Once you’ve identified the package you need, you can use pip to install it. Here’s
how you do it:
Example Installation Command:

bashCopy code
pip install requests

This command tells pip to download the requests package from PyPI and install it
in your Python environment.

3. Using the Installed Package


After installing a package, you can use it in your Python code. For example, with
the requests package installed, you can write a script to fetch data from a web API:

Example Code:

pythonCopy code
import requests

response = requests.get('https://api.github.com')
print(response.status_code) # Output: 200 (OK)
print(response.json()) # Output: JSON data from the API

Moduels and packages: 9


Additional Commands with pip
Upgrade a Package:

bashCopy code
pip install --upgrade requests

This command updates the requests package to the latest version available on
PyPI.

Uninstall a Package:

bashCopy code
pip uninstall requests

This command removes the requests package from your environment.

List Installed Packages:

bashCopy code
pip list

This command shows a list of all packages installed in your environment.

Show Package Information:

bashCopy code
pip show requests

This command provides detailed information about the requests package,


including its version, location, and dependencies.

Moduels and packages: 10


Modules How to use it :

1. math Module
The math module provides mathematical functions and constants.
Example: Basic Mathematical Operations

pythonCopy code
import math

# Constants
print("Value of pi:", math.pi) # Output: Value of p
i: 3.141592653589793
print("Value of e:", math.e) # Output: Value of e:
2.718281828459045

# Mathematical Functions
print("Square root of 16:", math.sqrt(16)) # Output: Squ
are root of 16: 4.0
print("Factorial of 5:", math.factorial(5)) # Output: Fact
orial of 5: 120
print("Cosine of 45 degrees:", math.cos(math.radians(45))) #
Output: Cosine of 45 degrees: 0.7071067811865476

2. os Module
The os module provides a way to interact with the operating system.
Example: File and Directory Operations

pythonCopy code
import os

# Get current working directory

Moduels and packages: 11


print("Current working directory:", os.getcwd()) # Output: C
urrent working directory: /path/to/directory

# List files and directories in a directory


print("Files and directories in /path/to/directory:", os.list
dir('/path/to/directory'))

# Create a new directory


os.mkdir('new_directory')
print("Directory 'new_directory' created.")

# Remove a file
os.remove('file_to_remove.txt')
print("File 'file_to_remove.txt' removed.")

3. random Module
The random module generates random numbers and selections.
Example: Generating Random Numbers and Choices

pythonCopy code
import random

# Random integer between 1 and 10


print("Random integer between 1 and 10:", random.randint(1, 1
0)) # Output: Random integer between 1 and 10: (e.g., 7)

# Random floating-point number between 0.0 and 1.0


print("Random float between 0.0 and 1.0:", random.random())
# Output: Random float between 0.0 and 1.0: (e.g., 0.54881350
39273248)

# Random choice from a list


choices = ['apple', 'banana', 'cherry']

Moduels and packages: 12


print("Random choice from the list:", random.choice(choices))
# Output: Random choice from the list: (e.g., 'banana')

# Shuffle a list
random.shuffle(choices)
print("Shuffled list:", choices) # Output: Shuffled list:
(e.g., ['banana', 'cherry', 'apple'])

4. pandas Module
The pandas module provides data structures and data analysis tools.
Example: DataFrame Operations

pythonCopy code
import pandas as pd

# Create a DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data)

# Display the DataFrame


print("DataFrame:")
print(df)

# Accessing a column
print("\nAges:")
print(df['Age'])

# Filtering rows
print("\nRows where Age > 30:")

Moduels and packages: 13


print(df[df['Age'] > 30])

# Basic statistics
print("\nStatistics:")
print(df.describe())

5. numpy Module
The numpy module provides support for large, multi-dimensional arrays and
matrices.
Example: Array Operations

pythonCopy code
import numpy as np

# Create a numpy array


arr = np.array([1, 2, 3, 4, 5])

Table: Modules vs. Packages vs. Libraries

Concept Definition Example Description

Modules are Python files that


A single file contain functions, classes, or
math.py ,
Module containing Python variables. They can be
utils.py
code. imported and used in other
Python scripts.

Packages are directories that


A collection of contain multiple modules and
modules organized in a special __init__.py file.
Package
directories with an They help organize related
__init__.py file. modules into a single
namespace.

Moduels and packages: 14


Libraries are larger
A collection of
collections of packages and
packages and
requests , modules designed to provide
modules that provide
Library scikit-learn specific functionalities or
a set of
, numpy , pandas solve particular problems.
functionalities or
They are often installed via
tools.
package managers.

Creating Modules and packages :

1. Creating a Module
A module is simply a Python file ( .py ) containing functions, classes, or variables
that you want to include in other programs.
Example: Creating a Module

Step 1: Create a Python file


Let's create a module named math_utils.py . This module will contain a few
mathematical functions.

pythonCopy code
# math_utils.py

def add(x, y):


return x + y

def subtract(x, y):


return x - y

def multiply(x, y):


return x * y

def divide(x, y):


if y == 0:
raise ValueError("Cannot divide by zero.")

Moduels and packages: 15


return x / y

Step 2: Use the Module


Create another Python file to use the functions from math_utils.py .

pythonCopy code
# main.py

import math_utils

print(math_utils.add(5, 3)) # Output: 8


print(math_utils.subtract(10, 4)) # Output: 6
print(math_utils.multiply(2, 3)) # Output: 6
print(math_utils.divide(10, 2)) # Output: 5.0

2. Creating a Package
A package is a directory containing multiple modules and a special file named
__init__.py .

Example: Creating a Package


Step 1: Create the Package Directory
Let's create a package named geometry that will contain modules for different
shapes.

plaintextCopy code
geometry/
__init__.py
circle.py
square.py
triangle.py

Moduels and packages: 16


Step 2: Define Modules within the Package
Create circle.py , square.py , and triangle.py inside the geometry directory.

circle.py :

pythonCopy code
# geometry/circle.py

import math

def area(radius):
return math.pi * (radius ** 2)

def circumference(radius):
return 2 * math.pi * radius

square.py :

pythonCopy code
# geometry/square.py

def area(side_length):
return side_length ** 2

def perimeter(side_length):
return 4 * side_length

triangle.py :

pythonCopy code
# geometry/triangle.py

def area(base, height):


return 0.5 * base * height

Moduels and packages: 17


def perimeter(side1, side2, side3):
return side1 + side2 + side3

Step 3: Create __init__.py

The __init__.py file can be empty or include initialization code for the package.

__init__.py :

pythonCopy code
# geometry/__init__.py

from .circle import area as circle_area, circumference as cir


cle_circumference
from .square import area as square_area, perimeter as square_
perimeter
from .triangle import area as triangle_area, perimeter as tri
angle_perimeter

Step 4: Use the Package


Create another Python file to use the functions from the package.

pythonCopy code
# main.py

from geometry import circle, square, triangle

print("Circle Area:", circle.area(5)) # Outp


ut: Circle Area: 78.53981633974483
print("Circle Circumference:", circle.circumference(5)) # Ou
tput: Circle Circumference: 31.41592653589793

print("Square Area:", square.area(4)) # Outp


ut: Square Area: 16

Moduels and packages: 18


print("Square Perimeter:", square.perimeter(4)) # Outp
ut: Square Perimeter: 16

print("Triangle Area:", triangle.area(5, 10)) # Outp


ut: Triangle Area: 25.0
print("Triangle Perimeter:", triangle.perimeter(3, 4, 5)) #
Output: Triangle Perimeter: 12

Summary
1. Creating a Module:

Create a .py file with functions or classes.

Import and use the module in other scripts.

2. Creating a Package:

Create a directory with modules and an __init__.py file.

Define modules with specific functionalities.

Use the package by importing from it in other scripts.

Summary of Differences
Module:

Type: Single file.

Purpose: Organize related code.

Example: math_utils.py .

Package:

Type: Directory with multiple modules and an __init__.py file.

Purpose: Organize related modules hierarchically.

Moduels and packages: 19


Example: geometry/ directory with circle.py , square.py .

Library:

Type: Collection of modules and packages.

Purpose: Provide a set of related functionalities.

Example: numpy , requests .

Moduels and packages: 20

You might also like