Unit 5 Python
Unit 5 Python
🔶 1. Python Packages
🔸 What is a Package in Python?
● A package is a collection of Python modules organized in directories.
● A package is essentially a folder that contains an __init__.py file and one or more
Python files (modules).
● Packages act like toolboxes, storing and organizing tools (functions and classes) for
efficient access and reuse.
1. Create a Directory: Make a directory for your package. This will serve as the root folder.
2. Add Modules: Add Python files (modules) to the directory, each representing specific
functionality.
3. Include __init__.py: Add an __init__.py file (can be empty) to the directory to mark it as
a package.
4. Add Sub packages (Optional): Create subdirectories with their own __init__.py files for
sub packages.
5. Import Modules: Use dot notation to import, e.g., from mypackage.module1 import
greet.
Example :
In this example, we are creating a Math Operation Package to organize Python code into a
structured package with two sub-packages: basic (for addition and subtraction) and advanced
(for multiplication and division). Each operation is implemented in separate modules, allowing
for modular, reusable and maintainable code.
math_operations/__init__.py:
This __init__.py file initializes the main package by importing and exposing the calculate
function and operations (add, subtract, multiply, divide) from the respective sub-packages for
easier access.
# Initialize the main package
from .calculate import calculate
from .basic import add, subtract
from .advanced import multiply, divide
math_operations/calculator.py:
This calculate file is a simple placeholder that prints "Performing calculation...", serving as a
basic demonstration or utility within the package.
def calculate():
print("Performing calculation...")
math_operations/basic/__init__.py:
This __init__.py file initializes the basic sub-package by importing and exposing the add and
subtract functions from their respective modules (add.py and sub.py). This makes these
functions accessible when the basic sub-package is imported.
math_operations/basic/add.py:
math_operations/basic/sub.py:
In the same way we can create the sub package advanced with multiply and divide modules.
Now, let's take an example of importing the module into a code and using the function:
Output:
6
8
Output:
➤ Purpose:
● Matplotlib is a Python library for data visualization, primarily used to create static,
animated, and interactive plots. It provides a wide range of plotting functions to visualize
data effectively.
Anatomy of a Matplotlib Plot: This section dives into the key components of a Matplotlib plot,
including figures, axes, titles, and legends, essential for effective data visualization.
The parts of a Matplotlib figure include (as shown in the figure above):
● Figure: The overarching container that holds all plot elements, acting as the canvas for
visualizations.
● Axes: The areas within the figure where data is plotted; each figure can contain multiple
axes.
● Axis: Represents the x-axis and y-axis, defining limits, tick locations, and labels for data
interpretation.
● Lines and Markers: Lines connect data points to show trends, while markers denote
individual data points in plots like scatter plots.
● Title and Labels: The title provides context for the plot, while axis labels describe what
data is being represented on each axis.
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
plt.plot(x, y, marker='o')
plt.title("Line Graph")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.grid(True)
plt.show()
➤ Functions:
Function Descriptio
n
hist() Histogram
Besides its obvious scientific uses, Numpy can also be used as an efficient multi-dimensional
container of generic data.
➤ Purpose:
➤ Features:
import numpy as np
➤ Important Functions:
Function Description
np.array( Create array
)
np.std() Standard
deviation
It offers functions for data transformation, aggregation and visualization, which are important for
analysis. Created by Wes McKinney in 2008, Pandas widely used by data scientists, analysts
and researchers worldwide. Pandas revolves around two primary Data structures: Series (1D)
for single columns and DataFrame (2D) for tabular data enabling efficient data manipulation.
➤ Purpose:
➤ Core Components:
● Series: One-dimensional
● DataFrame: Two-dimensional
import pandas as pd
print(df)
print(df.describe())
➤ Important Functions:
Function Description
iloc[], Indexing
loc[]
✅ Tkinter Basics
import tkinter as tk
root = tk.Tk()
root.title("Simple GUI")
root.geometry("300x200")
label = tk.Label(root, text="Hello, Tkinter!")
label.pack()
root.mainloop()
🔷 3. Tkinter Widgets
Widget Purpose
def greet():
name = entry.get()
label_result.config(text="Hello " + name)
root = Tk()
entry = Entry(root)
entry.pack()
button = Button(root, text="Submit", command=greet)
button.pack()
label_result = Label(root)
label_result.pack()
root.mainloop()
🔷 4. Tkinter Examples
✅ Example 1: Login Form
from tkinter import *
def login():
if entry_user.get() == "admin" and entry_pass.get() == "1234":
result.config(text="Login Successful")
else:
result.config(text="Invalid Credentials")
root = Tk()
Label(root, text="Username").pack()
entry_user = Entry(root)
entry_user.pack()
Label(root, text="Password").pack()
entry_pass = Entry(root, show='*')
entry_pass.pack()
root.mainloop()
def evaluate():
try:
result = eval(entry.get())
entry.delete(0, END)
entry.insert(0, result)
except:
entry.delete(0, END)
entry.insert(0, "Error")
root = Tk()
entry = Entry(root, width=30)
entry.pack()
● Code editor
● Debugging tools
● Terminal integration
● Auto-completion & syntax checking