Module-V
Python Packages
• A package is a way of organizing related modules into a directory hierarchy.
• A module is simply a .py file containing functions, classes, and variables.
• A package is a directory containing a special __init__.py file (can be empty), along with
multiple modules.
Why use packages?
• Organize large codebases
• Promote code reusability
• Easier to maintain and distribute
• Modular programming
Importing Packages and Modules
Syntax
import package_name
import package_name. module_name
from package_name import module_name
from package_name.module_name import function_name
Example:
import math
print([Link](16))
from datetime import datetime
print([Link]())
Built-in Packages
Package Purpose
math Mathematical functions
datetime Date and time manipulation
os Operating system interface
sys System-specific parameters and functions
Package Purpose
json JSON parsing and serialization
re Regular expressions
External Packages (need installation)
Package Purpose
numpy Numerical computing
pandas Data manipulation and analysis
matplotlib Data visualization
seaborn Statistical visualization
scikit-learn Machine learning
tensorflow Deep learning
flask Web development
tkinter GUI development
Simple programs using the built-in functions of packages matplotlib, numpy, pandas
Matplotlib
• matplotlib is a data visualization library.
• Common functions: plot(), bar(), hist(), scatter(), xlabel(), ylabel(),
title(), show()
Example: Simple Line Plot
import [Link] as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
[Link](x, y)
[Link]('Simple Line Plot')
[Link]('X-axis')
[Link]('Y-axis')
[Link](True)
[Link]()
Example: Bar Plot
import [Link] as plt
categories = ['A', 'B', 'C', 'D']
values = [10, 20, 15, 5]
[Link](categories, values)
[Link]('Bar Chart')
[Link]()
Example: Histogram
import [Link] as plt
import numpy as np
data = [Link](1000)
[Link](data, bins=30, edgecolor='black')
[Link]('Histogram')
[Link]()
Numpy
• is a package for numerical computing.
numpy
• Common functions: array(), mean(), std(), dot(), reshape(), linspace(),
arange()
Example 1: Array Operations
import numpy as np
arr = [Link]([1, 2, 3, 4, 5])
print("Array:", arr)
print("Mean:", [Link](arr))
print("Standard Deviation:", [Link](arr))
print("Sum:", [Link](arr))
print("Max:", [Link](arr))
print("Min:", [Link](arr))
Example 2: Matrix Multiplication
import numpy as np
A = [Link]([[1, 2], [3, 4]])
B = [Link]([[5, 6], [7, 8]])
print("Matrix A:\n", A)
print("Matrix B:\n", B)
print("Dot Product (A.B):\n", [Link](A, B))
Example 3: Generate Sequences
import numpy as np
print("Arange:", [Link](0, 10, 2))
print("Linspace:", [Link](0, 1, 5))
Pandas
• pandas is used for data manipulation and analysis.
• Built-in functions: DataFrame(), read_csv(), describe(), head(), tail(),
mean(), groupby(), sort_values()
Example 1: Creating a DataFrame
import pandas as pd
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
df = [Link](data)
print(df)
Example 2: Basic Operations
print("Summary Statistics:\n", [Link](include='all'))
print("First 2 Rows:\n", [Link](2))
print("Last Row:\n", [Link](1))
Example 3: Reading and Writing CSV
# Save to CSV
df.to_csv('[Link]', index=False)
# Read from CSV
df_new = pd.read_csv('[Link]')
print(df_new)
Example 4: Grouping and Sorting
data = {
'Category': ['A', 'B', 'A', 'C', 'B'],
'Value': [10, 20, 30, 40, 50]
}
df = [Link](data)
# Group by Category
grouped = [Link]('Category').mean()
print("Grouped by Category:\n", grouped)
# Sort by Value
sorted_df = df.sort_values(by='Value', ascending=False)
print("Sorted DataFrame:\n", sorted_df)
Introduction to GUI Programming
• GUI = Graphical User Interface
• Allows users to interact with applications using windows, buttons, labels, text
boxes, etc.
• More user-friendly compared to CLI (Command Line Interface).
Examples of GUI Applications:
• Web browsers
• Text editors
• Media players
• Scientific applications with graphical controls
Tkinter Introduction
• Tkinter is Python’s standard GUI library.
• Comes bundled with Python (no installation needed for most distributions).
• Provides tools to create:
o Windows
o Buttons
o Labels
o Textboxes
o Menus
o Frames
o Canvas and more!
Tkinter Architecture
• Tk() → main application window
• Widgets → visual elements (buttons, labels, etc.)
• Geometry Managers → layout control (pack, grid, place)
• mainloop() → event loop (keeps GUI running)
Basic Program Structure
import tkinter as tk
# Step 1: Create main window
root = [Link]()
# Step 2: Set window title and size
[Link]("My First GUI App")
[Link]("400x300")
# Step 3: Add widgets (example: Label)
label = [Link](root, text="Hello, Tkinter!", font=("Arial", 16))
[Link](pady=20)
# Step 4: Run the main event loop
[Link]()
Tkinter Widgets
Widget Purpose
Label Display text or image
Button Trigger an action
Entry Single-line text input
Text Multi-line text input
Checkbutton
Checkbox (boolean
option)
Widget Purpose
Radiobutton Radio button (choose one)
Listbox Display list of items
Frame
Container for grouping
widgets
Canvas Drawing shapes/graphics
Example 1: Button and Label
import tkinter as tk
def on_click():
[Link](text="Button Clicked!")
root = [Link]()
[Link]("Button Example")
label = [Link](root, text="Click the Button", font=("Arial", 14))
[Link](pady=10)
button = [Link](root, text="Click Me", command=on_click)
[Link]()
[Link]()
Example 2: Entry Widget (Input Field)
import tkinter as tk
def show_text():
user_input = [Link]()
[Link](text=f"You entered: {user_input}")
root = [Link]()
[Link]("Entry Example")
entry = [Link](root)
[Link](pady=10)
button = [Link](root, text="Submit", command=show_text)
[Link]()
label = [Link](root, text="")
[Link]()
[Link]()
Example 3: Checkbutton
import tkinter as tk
def show_selection():
result = "Selected" if [Link]() else "Not Selected"
[Link](text=result)
root = [Link]()
[Link]("Checkbutton Example")
var = [Link]()
check = [Link](root, text="Check me", variable=var, command=show_selection)
[Link](pady=10)
label = [Link](root, text="")
[Link]()
[Link]()
Example 4: Radiobutton
import tkinter as tk
def show_choice():
[Link](text=f"Selected option: {[Link]()}")
root = [Link]()
[Link]("Radiobutton Example")
var = [Link]()
r1 = [Link](root, text="Option 1", variable=var, value="Option 1",
command=show_choice)
r2 = [Link](root, text="Option 2", variable=var, value="Option 2",
command=show_choice)
[Link]()
[Link]()
label = [Link](root, text="")
[Link]()
[Link]()
Tkinter Widgets (Tk Widgets)
Widgets are the building blocks of a Tkinter GUI application.
Widget Purpose
Label Display text or image
Button Trigger an action
Entry Single-line text input
Text Multi-line text input
Checkbutton Checkbox (boolean option)
Radiobutton Radio button (choose one)
Listbox Display list of items
Frame Container for grouping widgets
Canvas Drawing shapes/graphics
Scale Slider for selecting a numeric value
Menu Create dropdown menus
Scrollbar Add scrolling to other widgets
Syntax for Adding a Widget
widget = WidgetName(parent_window, options...)
[Link]() # or .grid(), .place()
Common Widget Options
• text — text displayed
• font — font style/size
• bg — background color
• fg — foreground (text) color
• width, height — dimensions
Example 1: Label and Button
import tkinter as tk
def on_click():
[Link](text="Hello, Tkinter!")
root = [Link]()
[Link]("Label & Button")
label = [Link](root, text="Click the button", font=("Arial", 16))
[Link](pady=10)
button = [Link](root, text="Click Me", command=on_click)
[Link](pady=10)
[Link]()
Example 2: Entry and Label
import tkinter as tk
def show_text():
user_input = [Link]()
[Link](text=f"You entered: {user_input}")
root = [Link]()
[Link]("Entry Example")
entry = [Link](root)
[Link](pady=10)
button = [Link](root, text="Submit", command=show_text)
[Link](pady=10)
label = [Link](root, text="")
[Link]()
[Link]()
Example 3: Listbox with Scrollbar
import tkinter as tk
root = [Link]()
[Link]("Listbox Example")
listbox = [Link](root)
[Link](side=[Link], fill=[Link])
scrollbar = [Link](root)
[Link](side=[Link], fill=[Link])
[Link](yscrollcommand=[Link])
[Link](command=[Link])
for i in range(50):
[Link]([Link], f"Item {i+1}")
[Link]()
Example 4: Menu Bar
import tkinter as tk
def say_hello():
print("Hello from menu!")
root = [Link]()
[Link]("Menu Example")
menu_bar = [Link](root)
[Link](menu=menu_bar)
file_menu = [Link](menu_bar, tearoff=0)
file_menu.add_command(label="Say Hello", command=say_hello)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=[Link])
menu_bar.add_cascade(label="File", menu=file_menu)
[Link]()
Python Programming with IDE
What is an IDE?
IDE = Integrated Development Environment
It provides an interface to write, debug, and run Python code.
Popular IDEs for Python:
IDE/Editor Features
PyCharm Advanced, great for large projects, professional use
VS Code Lightweight, supports many languages, highly customizable
Jupyter Notebook Interactive notebook-based coding (great for data science)
Spyder MATLAB-like scientific IDE
How to use an IDE
Install Python and an IDE
Open the IDE
Create a new Python file (.py)
Write code in the file
Run the code using the Run button or terminal
Debug using breakpoints and step over features
Explore extensions and themes in IDE
Example Simple Project: GUI + Numpy + Pandas + Matplotlib
import tkinter as tk
import pandas as pd
import numpy as np
import [Link] as plt
def plot_graph():
x = [Link](0, 10, 100)
y = [Link](x)
[Link](x, y)
[Link]("Sine Wave")
[Link]()
root = [Link]()
[Link]("Integrated Example")
button = [Link](root, text="Plot Graph", command=plot_graph)
[Link](pady=20)
[Link]()