Unit 5
Syllabus
Python packages: Simple programs using the built-in functions of packages
matplotlib, numpy, pandas etc. GUI Programming: Tkinter introduction, Tkinter
and PythonProgramming, Tk Widgets, Tkinter examples. Python programming
with IDE.
Python packages:
Python packages are a way to organize and structure code by grouping related modules into
directories
A package is essentially a folder that contains an __init__.py file and one
or more Python files (modules).
Allows modules to be easily shared and distributed across different applications.
Key Components of a Python Package:
Module: A single Python file containing reusable code (e.g., [Link]).
Package: A directory containing modules and a special __init__.py file.
Sub-Packages: Packages nested within other packages for deeper organization.
Root Directory
Package
Package Marker
Package Marker
Module
Main Module
Example:
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.
__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.
from .packageProgram import add, sub, mul, div
[Link]:
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
def div(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 main function:
[Link]:
from packageProgram import add, sub, mul, div
a = int(input("Enter a values : "))
b = int(input("Enter b values : "))
x = add(a,b)
y = sub(a,b)
z = mul(a,b)
d= div(a,b)
print("Addition =", x)
print("Subtraction =", y)
print("Multiply =", z)
print("Division =", d)
Run Program:
Data Visualization:
Data visualization is the graphical representation of information and data. It uses visual
elements like charts, graphs, and maps to help people understand complex data, identify
patterns, trends, and outliers in data sets.
Matplotlib
Seaborn
Plotly
Bokeh
Altair
Pygal
Plotnine
Dash
Matplotlib
Matplotlib is a powerful, low-level Python library for creating static, interactive, and
animated data visualizations in Python.
Key Features of Matplotlib:
Customization: Matplotlib gives you full control over every element of a figure,
including the figure size, font style, line properties, axes, and more.
Variety of Plots: It supports a vast array of plot types, including:
Line plots
Scatter plots
Bar charts
Histograms
Box plots
3D plots
Anatomy of a Matplotlib Figure:
Figure: The entire window or canvas where everything is drawn. It holds all the
plots and their respective components.
Axes: This is the actual plot where the data is drawn. A Figure can contain multiple
Axes. It has an x-axis and a y-axis, ticks, and labels.
Title: A descriptive text for the entire plot.
Labels: Text labels for the $x$-axis and $y$-axis to describe what the data
represents.
Legend: Identifies what each line or color represents in the plot.
Installation of Matplotlib
If you have Python and PIP already installed on a system, then installation of Matplotlib is
very easy.
Install it using this command:
C:\Users\Your Name>pip install matplotlib
Import Matplotlib with Pyplot
Once Matplotlib is installed, import it in your applications by adding the import module
statement
import [Link] as plt
Markers
You can use the keyword argument marker to emphasize each point with a specified marker
Example : Basic Example Matplotlib
Example Output
import [Link] as plt
# Data points (x-axis & y-axis)
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]
# Plot graph
[Link](x, y, marker='o')
# Title & Labels
[Link]("Simple Line Graph using
Matplotlib created by Pankaj
Kumar Gupta")
[Link]("X - Axis (Days)")
[Link]("Y - Axis (Values)")
# Show graph
[Link]()
Bar plot Matplotlib:
A bar plot uses rectangular bars to represent data categories, with bar length or height
proportional to their values
Compares discrete categories, with one axis for categories and the other for values.
Example Output
import [Link] as plt
fruits = ['Apples', 'Bananas', 'Cherries',
'Dates']
sales = [400, 350, 300, 450]
[Link](fruits, sales)
[Link]('Fruit Sales')
[Link]('Fruits')
[Link]('Sales')
[Link]()
Customizing Bar Colour:
Example Output
import [Link] as plt
fruits = ['Apples', 'Bananas',
'Cherries', 'Dates']
sales = [400, 350, 300, 450]
[Link](fruits, sales, color='green')
[Link]('Fruit Sales')
[Link]('Fruits')
[Link]('Sales')
[Link]()
Creating Horizontal Bar Plots:
Example Outpiut
import [Link] as plt
fruits = ['Apples', 'Bananas',
'Cherries', 'Dates']
sales = [400, 350, 300, 450]
[Link](fruits, sales)
[Link]('Fruit Sales')
[Link]('Fruits')
[Link]('Sales')
[Link]()
Creation Grid Bar plots:
Example Output
import [Link] as plt
fruits = ['Apples', 'Bananas',
'Cherries', 'Dates']
sales = [400, 350, 300, 450]
[Link](fruits, sales, color='red')
[Link]('Fruit Sales')
[Link]('Fruits')
[Link]('Sales')
[Link]()
[Link]()
Creating Scatter plots:
Example Output
import [Link] as
plt
x=[1,2,3,4,5,6]
y=[10,40,25,20,35,50]
[Link]('Simple Graph using
Scatter')
[Link]('x-Axis')
[Link]('y-axis')
[Link](x,y)
[Link]()
[Link]()
Pie Chart:
A pie chart consists of slices that represent different categories.
The size of each slice is proportional to the quantity it represents.
The following components are essential when creating a pie chart in Matplotlib.
Data: The values or counts for each category.
Labels: The names of each category, which will be displayed alongside the slices.
Colors: Optional, but colors can be used to differentiate between slices effectively.
Example Output
import [Link] as plt
# Data
subjects = ["Math", "Python",
"DBMS", "OS", "Networking"]
marks = [80, 75, 65, 70, 60]
# Plot Pie Chart
[Link](figsize=(6,6))
[Link](marks, labels=subjects)
# Title
[Link]("Subject Wise Marks (Pie
Chart) ")
# Show Chart
[Link]()
Example Output
from matplotlib import pyplot as
plt
# Creating data point
cars = ['AUDI', 'BMW', 'FORD',
'TESLA', 'JAGUAR',
'MERCEDES']
data = [23, 17, 35, 29, 12, 41]
# Creating plot
[Link](data, labels=cars)
# show plot
[Link]()
NumPy
NumPy stands for Numerical Python.
NumPy is a Python library used for working with arrays.
It also has functions for working in domain of linear algebra, fourier transform, and
matrices.
Use NumPy
We have lists that serve the purpose of arrays, but they are slow to process.
NumPy aims to provide an array object that is faster than traditional Python lists.
The array object in NumPy is called ndarray, it provides a lot of supporting functions
that make working with ndarray very easy.
Installation NumPy
C:\Users\Your Name>pip install numpy
Import NumPy
import numpy as np
Example Output
Import numpy as np [1,2,3,4,5,66,88,11,55]
arr=[Link]([1,2,3,4,5,66,88,11,55])
print(arr)
Dimensions in Arrays
0-D Arrays: O-D arrays, or Scalars, are the elements in an array. Each value in an
array is a 0-D array.
Example Output
import numpy as np 42
arr = [Link](42)
print(arr)
1-D Arrays:
Example Output
import numpy as np [1, 2, 3, 4, 5]
arr = [Link]([1, 2, 3, 4, 5])
print(arr)
2-D Arrays:
An array that has 1-D arrays as its elements is called a 2-D array.
Example Output
import numpy as np [[1, 2, 3], [4, 5, 6]]
arr = [Link]([[1, 2, 3], [4, 5, 6]])
print(arr)
3-D arrays
Example Output
import numpy as np [[[1, 2, 3], [4, 5, 6]], [[1, 2, 3],
[4, 5, 6]]]
arr = [Link]([[[1, 2, 3], [4, 5, 6]],
[[1, 2, 3], [4, 5, 6]]])
print(arr)
NumPy Array Indexing:
Array indexing is the same as accessing an array element.
You can access an array element by referring to its index number.
Access Array Elements
Example Output
import numpy as np 1
arr = [Link]([1, 2, 3, 4])
print(arr[0])
Example2 Output
import numpy as np 7
arr = [Link]([1, 2, 3, 4])
print(arr[2] + arr[3])
Access 2-D Arrays:
To access elements from 2-D arrays we can use comma separated integers
representing the dimension and the index of the element.
Example Output
import numpy as np 2nd element on 1st row: 2
arr = [Link]([[1,2,3,4,5], [6,7,8,9,10]])
print('2nd element on 1st row: ', arr[0, 1])
Sorting Arrays:
Sorting means putting elements in an ordered sequence
Ordered sequence is any sequence that has an order corresponding to elements, like
numeric or alphabetical, ascending or descending.
Example Output
import numpy as np [0,1,2,3]
arr = [Link]([3, 2, 0, 1])
print([Link](arr))
Example2 Output
import numpy as np [‘apple’, banana’, ‘cherry’]
arr = [Link](['banana', 'cherry', 'apple'])
print([Link](arr))
Random Numbers in NumPy:
Random number does NOT mean a different number every time. Random means something
that can not be predicted logically.
Generate Random Float
Example Output
import numpy as np 0.025642458
rn= [Link]()
print(rn)
Integers:
The randint() method takes a size parameter where you can specify the shape of an array.
Generate a 1-D array containing 5 random integers from 0 to 100:
Example Output
import numpy as np [81 6 66 18 10 ]
x=[Link](100, size=(5))
print(x)
Generate a 2-D array with 3 rows, each row containing 5 random integers from 0 to
100:
Example Output
import numpy as np [[60 17 89 76 28]
x = [Link](100, size=(3, 5)) [64 21 57 31 50]
print(x) [50 64 87 7 22]]
Question: Describ how to generate random numbers using NumPy. Write a program to
create an array of 5 random integers between 10 and 50.
Solution
NumPy provides a submodule called [Link] that is used to generate random
numbers. With this module, we can generate.
Random integers
Random floating-point numbers
Random arrays
1. [Link](low, high, size)
Generates random integers
low = starting value (inclusive)
high = ending value (exclusive)
size = number of random values or array shape
2. [Link]()
Generates random float numbers between 0 and 1
NumPy makes random number generation fast and easy, especially for scientific and data-
science applications.
Program:
import numpy as np
arr = [Link](10, 51, size=5)
print("Random numbers:", arr)
Pandas:
Pandas is a Python library used for working with data sets.
It has functions for analyzing, cleaning, exploring, and manipulating data.
Pandas can clean messy data sets, and make them readable and relevant.
Installation of Pandas:
C:\Users\Your Name>pip install pandas
Import Pandas:
Import pandas as pd
Example Output
import pandas as pd
mydataset = {
'cars': ["BMW", "Volvo", "Ford"],
'passings': [3, 7, 2]
}
myvar = [Link](mydataset)
print(myvar)
Pandas Series:
A Pandas Series is like a column in a table.
It is a one-dimensional array holding data of any type.
Example Output
import pandas as pd
a = [1, 7, 2]
myvar = [Link](a)
print(myvar)
Example2 Output
import pandas as pd
a = [1, 7, 2]
myvar = [Link](a, index = ["x", "y", "z"])
print(myvar)
Key/Value Objects as Series:
Example Output
import pandas as pd
calories = {"day1": 420, "day2": 380,
"day3": 390}
myvar = [Link](calories)
print(myvar)
DataFrames:
Data sets in Pandas are usually multi-dimensional tables, called DataFrames.
Create a DataFrame from two Series:
Example Output
import pandas as pd
data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}
myvar = [Link](data)
print(myvar)
Named Indexes:
Add a list of names to give each row a name:
Example Output
import pandas as pd
data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}
df = [Link](data, index =
["day1", "day2", "day3"])
print(df)
Pandas read csv:
A simple way to store big data sets is to use CSV files (comma separated files).
CSV files contains plain text and is a well know format that can be read by everyone
including Pandas.
Create a [Link] file
Data Store in [Link] file
name,rollNo,mobileNumber,emailid
Goel,12345678,8564865923,goel@[Link]
Abhishek,7854215,63452158695,abhi@[Link]
Abhimanu,4512542,7854215869,manu@[Link]
Example Output
import pandas as pd
with open(r"D:\New
folder\[Link]\[Link]"
, 'r') as file1:
df = pd.read_csv(file1)
print(df)
Question: Write a program to read data from a CSV file '[Link]', calculate the
average marks for each student, and display the results.
Solution
name,python,java,OS,WT,DS
Abhishek,28,55,26,44,31 [Link]
Abhimanu, 30,45,30,35,45
Ballu,32,35,28,50,32
Program
import pandas as pd
with open(r'D:\New folder\[Link]\[Link]','r') as file:
dataFrame1= pd.read_csv(file)
print(dataFrame1)
print("**********************************************")
dataFrame1["Average"] =
dataFrame1[['python','java','OS','WT','DS']].mean(axis=1)
print(dataFrame1[['name','Average']])
GUI Programming:
GUI stands for Graphical User Interface.
It is a type of user interface that allows users to interact with a computer program
using graphical components.
Button
Text boxes
Labels
Menus
Windows
Dialog boxes
Popular GUI Libraries in Python
1. Tkinter:
Built-in Python library
Simple and widely used
Provides widgets like Button, Label, Entry, Frame, etc.
2. PyQt / PySide
3. Kivy
4. wxPython
Example Output
import tkinter as tk
root = [Link]()
[Link]("My First GUI")
label = [Link](root, text="Hello,
GUI in Python!")
[Link]()
[Link]()
Button:
A button is a clickable widget. When the user clicks it, a function is executed.
Example Output
import tkinter as tk
def click_me():
print("Button Clicked!")
root = [Link]()
[Link]("Button Example")
btn = [Link](root, text="Click
Me", command=click_me)
[Link]()
[Link]()
Text Box (Entry):
A text box allows the user to type input.
Example Output
import tkinter as tk
root = [Link]()
[Link]("Textbox Example")
entry = [Link](root)
[Link]()
[Link]()
Label:
A label is used to display text or an image on the window.
Example Output
import tkinter as tk
root = [Link]()
[Link]("Label Example")
label = [Link](root, text="This is a
Label")
[Link]()
[Link]()
Menu:
A menu appears at the top of the window, like “File”, “Edit”.
Example Output
import tkinter as tk
root = [Link]()
[Link]("Menu Example")
menubar = [Link](root)
file_menu = [Link](menubar,
tearoff=0)
file_menu.add_command(label="Open")
file_menu.add_command(label="Save")
file_menu.add_separator() Click on file
file_menu.add_command(label="Exit",
command=[Link])
menubar.add_cascade(label="File",
menu=file_menu)
[Link](menu=menubar)
[Link]()
Window:
The main window is the central container where all Tkinter widgets are placed.
Example Output
import tkinter as tk
root = [Link]()
[Link]("Main Window Example")
[Link]("300x200")
[Link]()
Dialog Box (Messagebox):
A dialog box is a pop-up message that can show info, warnings, or errors.
Example Output
import tkinter as tk
from tkinter import messagebox
def show_msg():
[Link]("Information",
"This is a dialog box")
Click on Show Dialog
root = [Link]()
[Link]("Dialog Example")
btn = [Link](root, text="Show Dialog",
command=show_msg)
[Link]()
[Link]()
Simple Calculator using Tkinter
Program
import tkinter as tk
from tkinter import messagebox
# ------------------- Functions -------------------
def add_digit(digit):
[Link]([Link], digit)
def clear_entry():
[Link](0, [Link])
def calculate():
try:
expression = [Link]()
result = eval(expression)
[Link](0, [Link])
[Link](0, str(result))
except:
[Link]("Error", "Invalid Expression") # Dialog Box
def show_about():
[Link]("About", "Simple Calculator using Tkinter") # Dialog Box
# ------------------- Main Window -------------------
root = [Link]()
[Link]("Calculator Project")
[Link]("300x400")
# ------------------- Menu Bar -------------------
menubar = [Link](root)
# File Menu
file_menu = [Link](menubar, tearoff=0)
file_menu.add_command(label="Clear", command=clear_entry)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=[Link])
menubar.add_cascade(label="File", menu=file_menu)
# Help Menu
help_menu = [Link](menubar, tearoff=0)
help_menu.add_command(label="About", command=show_about)
menubar.add_cascade(label="Help", menu=help_menu)
[Link](menu=menubar)
# ------------------- Label -------------------
label = [Link](root, text="Calculator", font=("Arial", 18), bd=3, relief="solid")
[Link](pady=10)
# ------------------- Textbox (Entry) -------------------
entry = [Link](root, font=("Arial", 16), bd=5, relief="sunken", justify="right")
[Link](fill="x", padx=10, pady=10)
# ------------------- Buttons -------------------
frame = [Link](root)
[Link]()
buttons = [
("7", 0, 0), ("8", 0, 1), ("9", 0, 2), ("/", 0, 3),
("4", 1, 0), ("5", 1, 1), ("6", 1, 2), ("*", 1, 3),
("1", 2, 0), ("2", 2, 1), ("3", 2, 2), ("-", 2, 3),
("0", 3, 0), (".", 3, 1), ("=", 3, 2), ("+", 3, 3),
]
for (text, row, col) in buttons:
if text == "=":
btn = [Link](frame, text=text, width=5, height=2,
command=calculate, bg="lightgreen")
else:
btn = [Link](frame, text=text, width=5, height=2,
command=lambda t=text: add_digit(t))
[Link](row=row, column=col, padx=5, pady=5)
[Link]()
Output
Python Programming with IDE:
IDE (Integrated Development Environment) is a software
Write Python code
Run programs
Fix errors
See output
Manage files
Use auto-suggestions & debugging tools
Popular IDEs for Python:
VS Code
PyCharm
Jupyter Notebook.. etc
Simple Program Output
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
def div(a, b):
return a / b
print("Simple Calculator")
x = float(input("Enter first number:
"))
y = float(input("Enter second number:
"))
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
choice = int(input("Enter your choice:
"))
if choice == 1:
print("Result:", add(x, y))
elif choice == 2:
print("Result:", sub(x, y))
elif choice == 3:
print("Result:", mul(x, y))
elif choice == 4:
print("Result:", div(x, y))
else:
print("Invalid choice")