[go: up one dir, main page]

0% found this document useful (0 votes)
3 views11 pages

Unit 5 Python

The document covers Python packages and GUI programming, explaining the structure and benefits of packages, and how to create and use them. It introduces commonly used libraries like Matplotlib, NumPy, and Pandas for data visualization and analysis, as well as Tkinter for building graphical user interfaces. Additionally, it discusses the advantages of using Integrated Development Environments (IDEs) for Python programming.

Uploaded by

shersingh9648
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)
3 views11 pages

Unit 5 Python

The document covers Python packages and GUI programming, explaining the structure and benefits of packages, and how to create and use them. It introduces commonly used libraries like Matplotlib, NumPy, and Pandas for data visualization and analysis, as well as Tkinter for building graphical user interfaces. Additionally, it discusses the advantages of using Integrated Development Environments (IDEs) for Python programming.

Uploaded by

shersingh9648
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/ 11

✅ UNIT V – PYTHON PACKAGES & GUI PROGRAMMING

🔶 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.

🔸 Why Use Packages?


●​ To organize code logically into smaller, reusable modules.
●​ Promotes code reusability, maintainability, and modular development.

Key Components of a Python Package

●​ Module: A single Python file containing reusable code (e.g., math.py).


●​ Package: A directory containing modules and a special __init__.py file.
●​ Sub-Packages: Packages nested within other packages for deeper organization.

How to create and access packages in python

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.

# Export functions from the basic sub-package


from .add import add
from .sub import subtract

math_operations/basic/add.py:

def add(a, b):


return a + b

math_operations/basic/sub.py:

def subtract(a, b):


return a - b

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:

from math_operations import calculate, add, subtract



# Using the placeholder calculate function
calculate()

# Perform basic operations
print("Addition:", add(5, 3))
print("Subtraction:", subtract(10, 4))

Output:

6
8

📘 Commonly Used Built-in Packages


✅ a. matplotlib
Matplotlib is a powerful and versatile open-source plotting library for Python, designed to help
users visualize data in a variety of formats. Developed by John D. Hunter in 2003, it enables
users to graphically represent data, facilitating easier analysis and understanding. If you want to
convert your boring data into interactive plots and graphs, Matplotlib is the tool for you.

Example of a Plot in Matplotlib:


Let's create a simple line plot using Matplotlib, showcasing the ease with which you can
visualize data.

import matplotlib.pyplot as plt



x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]​
plt.plot(x, y)
plt.show()

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.

Components or Parts of Matplotlib Figure

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.

➤ Key Module: pyplot


Pyplot is a module within Matplotlib that provides a MATLAB-like interface for making plots. It
simplifies the process of adding plot elements such as lines, images, and text to the axes of the
current figure.

import matplotlib.pyplot as plt

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()

Different Types of Plots in Matplotlib


Matplotlib offers a wide range of plot types to suit various data visualization needs. Here are
some of the most commonly used types of plots in Matplotlib:
1. Line Graph
2. Bar Chart
3. Histogram
4. Scatter Plot
5. Pie Chart
6. 3D Plot
and many more..

➤ Functions:
Function Descriptio
n

plot() Line graph

bar() Bar chart

scatter Scatter plot


()

hist() Histogram

pie() Pie chart

✅ b. numpy (Numerical Python)


Numpy is a general-purpose array-processing package. It provides a high-performance
multidimensional array object and tools for working with these arrays. It is the fundamental
package for scientific computing with Python.

Besides its obvious scientific uses, Numpy can also be used as an efficient multi-dimensional
container of generic data.

➤ Purpose:

●​ Fast numerical computations with multi-dimensional arrays.

➤ Features:

●​ Mathematical operations: mean, median, std deviation.


●​ Array creation: np.array(), np.arange(), np.zeros()​

import numpy as np

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


print("Mean:", np.mean(arr))
print("Sum:", np.sum(arr))
print("Std Dev:", np.std(arr))

➤ Important Functions:
Function Description
np.array( Create array
)

np.mean() Mean value

np.std() Standard
deviation

np.dot() Dot product

np.reshap Change shape


e()

✅ c. pandas (Python Data Analysis Library)


Pandas is an open-source software library designed for data manipulation and analysis. It
provides data structures like series and DataFrames to easily clean, transform and analyze
large datasets and integrates with other Python libraries, such as NumPy and Matplotlib.

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:

●​ High-level data manipulation and analysis tools.

➤ Core Components:

●​ Series: One-dimensional​

●​ DataFrame: Two-dimensional

import pandas as pd

data = {'Name': ['A', 'B', 'C'], 'Score': [90, 80, 70]}


df = pd.DataFrame(data)

print(df)
print(df.describe())
➤ Important Functions:
Function Description

read_csv() Read CSV file

head() Display first rows

describe() Summary stats

groupby() Group by column

iloc[], Indexing
loc[]

🔶 2. GUI Programming with Tkinter


✅ What is GUI Programming?
●​ GUI (Graphical User Interface): Programs with buttons, textboxes, labels, etc.
●​ Tkinter is Python's built-in GUI toolkit.
●​ Event-driven programming model: responds to user actions.

✅ 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

Label Displays text or image

Button Triggers a function on click


Entry Accepts user input (single line)

Text Multi-line input

Checkbutt Select multiple options


on

Radiobutt Choose one from many


on

Listbox Display a list

➤ Example: Input and Output


from tkinter import *

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()

Button(root, text="Login", command=login).pack()


result = Label(root)
result.pack()

root.mainloop()

✅ Example 2: Simple Calculator


from tkinter import *

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()

Button(root, text="Calculate", command=evaluate).pack()


root.mainloop()

🔷 5. Python Programming using IDE (15 Marks)


✅ What is an IDE?
An IDE (Integrated Development Environment) is a software suite that provides:

●​ Code editor
●​ Debugging tools
●​ Terminal integration
●​ Auto-completion & syntax checking

✅ Common IDEs for Python:


IDE Features

PyCharm Professional IDE by JetBrains, has debugging, version control, plugin


support

VS Code Lightweight, extension-based, real-time collaboration

Thonny Best for beginners, debugger is visual and easy to understand

✅ Benefits of Using IDEs:


●​ Faster coding with auto-suggestions.
●​ Error detection while typing.
●​ Integrated terminal for running code directly.
●​ Helps with project management and version control (Git integration).

✅ Writing & Running Python in IDE:


1.​ Open IDE → Create Project/File
2.​ Write Python code
3.​ Press Run or use terminal: python filename.py

You might also like