0% found this document useful (0 votes)
54 views

PP_unit-5_notes

Python aktu unit 5 notes.

Uploaded by

sia12sia2
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)
54 views

PP_unit-5_notes

Python aktu unit 5 notes.

Uploaded by

sia12sia2
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/ 15

Unit – 5

Introduction to Python Packages

Lecture 26. Python Packages


5.1 Python Packages- Python packages are a way of organizing and distributing Python code. They allow you to
bundle multiple files or modules into a single, importable package, making code reuse and distribution easier.
Python packages can include libraries, frameworks, or collections of modules that provide additional functionality or
enable specific tasks. Here's an overview of key concepts and steps related to Python packages:
Key Concepts
Module: A Python file containing Python definitions, statements, and functions. It's the smallest unit of code reuse in
Python.
Package: A way of collecting related modules together within a single tree-like hierarchy. Very complex packages
mayinclude subpackages at various levels of the hierarchy.
Installing Packages
To install packages, you generally use pip, Python's package installer
Commonly Used Packages
Here are some widely used Python packages for various purposes:
NumPy: Numerical computing and array operations.
Pandas: Data analysis and manipulation.
Requests: HTTP requests for humans.

5.2 Matplotlib
Matplotlib is a popular Python library used for creating static, animated, and interactive visualizations in Python. It
provides a wide range of plotting tools and features for creating high-quality graphs, charts, and plots.
Here are some of the key components and functions provided by Matplotlib:
Key Components:
Figure: The entire window or page where the plots and charts are drawn.
Axes: The area where data is plotted. It includes the X-axis, Y-axis, and the plot itself.
Axis: The X-axis and Y-axis, which define the scale and limits of the plot.
Artist: Everything that is drawn on the figure (such as lines, text, shapes) is an artist.
Installation:-
python -m pip install -U matplotlib

100
Matplotlib
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data
visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by
John Hunter in 2002.
Types of Matplotlib
Matplotlib comes with a wide variety of plots. Plots help to understand trends, and patterns, and to make correlations.
They’re typically instruments for reasoning about quantitative information.
Some of the sample plots are covered here.
Matplotlib Line Plot
Matplotlib Bar Plot
Matplotlib Histograms
Plot Matplotlib Scatter
Plot Matplotlib Pie Charts
Matplotlib Area Plot

5.2.1 Matplotlib Line Plot

By importing the matplotlib module, defines x and y values for a plotPython, plots the data using the plot() function and
it helps to display the plot by using the show() function . The plot() creates a line plot by connecting the points defined
by x and y values.
Eg:-
# importing matplotlib module
from matplotlib import pyplot as plt
# x-axis values
x = [5, 2, 9, 4, 7]
# Y-axis values
y = [10, 5, 8, 4, 2]
# Function to plot
plt.plot(x, y)
# function to show the plot
plt.show()
5.2.2 Matplotlib Bar Plot

# importing matplotlib module


from matplotlib import pyplot as plt
# x-axis valuesx = [5, 2, 9, 4, 7]

101
# Y-axis values
y = [10, 5, 8, 4, 2]
# Function to plot the bar
plt.bar(x, y)
# function to show the plot
plt.show()

5.2.3 Matplotlib Histograms Plot

# importing matplotlib module


from matplotlib import pyplot as plt

# Y-axis values
y = [10, 5, 8, 4, 2]

# Function to plot histogram


plt.hist(y)

# Function to show the plot


plt.show()

5.2.4 Matplotlib Scatter Plot

# importing matplotlib module


from matplotlib import pyplot as plt

# x-axis values
x = [5, 2, 9, 4, 7]

# Y-axis values
y = [10, 5, 8, 4, 2]

# Function to plot scatter


plt.scatter(x, y)

# function to show the plot


plt.show()

5.2.5 Matplotlib Pie Charts

import matplotlib.pyplot as plt

# Data for the pie chart


labels = ['Geeks 1', 'Geeks 2', 'Geeks 3']
sizes = [35, 35, 30]

# Plotting the pie chart


102
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
plt.title('Pie Chart Example')
plt.show()

5.2.6 Matplotlib Area Plot


import matplotlib.pyplot as plt
# Data
x = [1, 2, 3, 4, 5]
y1, y2 = [10, 20, 15, 25, 30], [5, 15, 10, 20, 25]

# Area Chart
plt.fill_between(x, y1, y2, color='skyblue', alpha=0.4, label='Area 1-2')
plt.plot(x, y1, label='Line 1', marker='o')
plt.plot(x, y2, label='Line 2', marker='o')

# Labels and Title


plt.xlabel('X-axis'),
plt.ylabel('Y-axis'),
plt.title('Area Chart Example')

# Legend and Display


plt.legend(),
plt.show()
Lecture 27. Python NumPy

5.3 Numpy:-

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. It is open-
source software.

5.3.1 Features of NumPy


NumPy has various features including these important ones:
● A powerful N-dimensional array object
● Sophisticated (broadcasting) functions
● Tools for integrating C/C++ and Fortran code
● Useful linear algebra, Fourier transform, and random number capabilities

Install Python
NumPypip install
numpy

Create a NumPy ndarray Object


NumPy is used to work with arrays. The array object in NumPy is called ndarray. We can create a
NumPy ndarray object by using the array() function.

Eg:-
import numpy as np

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

To create an ndarray, we can pass a list, tuple or any array-like object into the array() method, and it will be converted
into an ndarray:

Dimensions in Arrays

NumPy arrays can have multiple dimensions, allowing users to store data in multilayered structures.
Dimensionalities of array:

Name Example

0D (zero-dimensional) Scalar – A single element

1D (one-dimensional) Vector- A list of integers.

2D (two-dimensional) Matrix- A spreadsheet of data

Name Example

3D (three-dimensional) Tensor- Storing a color image

2-D Arrays

An array that has 1-D arrays as its elements is called a 2-D array.

These are often used to represent matrix or 2nd order tensors.

Example:-
import numpy as np

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

print(arr)

3-D arrays

Example:
import numpy as np

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

print(arr)

104
Lecture 28. Python Pandas

5.4 Introduction to Pandas


Pandas is a name from “Panel Data” and is a Python library used for data manipulation and analysis.
Pandas provides a convenient way to analyze and clean data. The Pandas library introduces two new data structures to
Python - Series and DataFrame, both of which are built on top of NumPy.

Why Use Pandas?


1. Handle Large Data Efficiently
2. Tabular Data Representation
3. Data Cleaning and Preprocessing
4. Free and Open-Source

Install Pandas
To install pandas, you need Python and PIP installed in your system.
If you have Python and PIP installed already, you can install pandas by entering the following command in the
terminal:
pip install pandas
Import Pandas in Python We can import Pandas in Python using the import statement.
import pandas as pd
What can you do using Pandas?
Pandas are generally used for data science but have you wondered why? This is because pandas are used in conjunction
with other libraries that are used for data science. It is built on the top of the NumPy library which means that a lot of
structures of NumPy are used or replicated in Pandas. The data produced by Pandas are often used as input for plotting
functions of Matplotlib, statistical analysis in SciPy, and machine learning algorithms in Scikit-learn. Here is a list of
things that we can do using Pandas.
● Data set cleaning, merging, and joining.
● Easy handling of missing data (represented as NaN) in floating point as well as non-floating point data.
● Columns can be inserted and deleted from DataFrame and higher dimensional objects.
● Powerful group by functionality for performing split-apply-combine operations on data sets.
● Data Visulaization

Pandas Data Structures


Pandas generally provide two data structures for manipulating data, They are:
● Series
● DataFrame

Pandas Series
A Pandas Series is a one-dimensional labeled array capable of holding data of any type (integer, string, float, python
objects, etc.). The axis labels are collectively called indexes.
Pandas Series is nothing but a column in an Excel sheet. Labels need not be unique but must be a hashable type. The
object supports both integer and label-based indexing and provides a host of methods for performing operations
involving the index.
105
Example 1:

# import pandas as pd
import pandas as pd

# simple array
data = [1, 2, 3, 4]

ser = pd.Series(data)
print(ser)

Example 2:-
# import pandas as pd
import pandas as pd

# import numpy as np
import numpy as np

# simple array
data = np.array(['g','e','e','k','s'])

ser = pd.Series(data)
print(ser)

DataFrame
Pandas DataFrame is a two-dimensional data structure with labeled axes (rows and columns).
Creating Data Frame
In the real world, a Pandas DataFrame will be created by loading the datasets from existing storage, storage can be
SQL Database, CSV file, or an Excel file. Pandas DataFrame can be created from lists, dictionaries, and from a list
of dictionaries, etc.
Example:-
import pandas as pd

# Calling DataFrame constructor


df = pd.DataFrame()
print(df)

# list of strings
lst = ['Geeks', 'For', 'Geeks', 'is', 'portal', 'for', 'Geeks']

# Calling DataFrame constructor on


list df = pd.DataFrame(lst)
print(df)

106
Lecture 29. GUI Programs

5.5 Hello World Window:


import tkinter as tk

# Create the main window


root = tk.Tk()
root.title("Hello World")

# Create a label widget with "Hello, World!" text


label = tk.Label(root, text="Hello, World!")
label.pack()

# Run the main event loop


root.mainloop()

Q:- Python Tkinter Program to show onclick event on button


Source Code:
import Tkinter as tk
root=tk.Tk()
def click():
a=e.get()
a1="Hello "+a
l1.config(text=a1
)
l=tk.Label(root,text="name",fg="red",bg="lightgreen")
l.grid(row=0,column=0)
l1=tk.Label(root)
l1.grid(row=1,column=1)
e=tk.Entry(root)
e.grid(row=0,column=1)
b=tk.Button(root,text="click",fg="red",bg="blue",command=click)
b.grid(row=1,column=0)
#button =tk.Button(root, text="Quit", command=root.destroy)

root.mainloop()

OUTPUT

107
Lecture 30. Tkinter and Python Programming

5.6 Tkinter

Python provides various options for developing graphical user interfaces (GUIs). Most important are listed below.

● Tkinter− Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We would look this
option in this chapter.
● wxPython− This is an open-source Python interface for wxWindow shttp://wxpython.org.
● JPython− JPython is a Python port for Java which gives Python scripts seamless access to Java class
libraries on the local machine http://www.jython.org
Tkinter Programming
Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast and easy way to
create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit.
Creating a GUI application using Tkinter is an easy task. All you need to do is perform the following steps .
● Import the Tkinter module.
● Create the GUI application main window.
● Add one or more of the above-mentioned widgets to the GUI application.
● Enter the main event loop to take action against each event triggered by the user.

Tk provides the following widgets:


● button
● canvas
● checkbutton
● combobox
● entry
● frame
● label
● labelframe
● listbox
● menu
● menubutton
● message
● notebook
● tk_optionMenu
● progressbar
● radiobutton
● scale
● scrollbar
● separator
● sizegrip
● spinbox
● text
● treeview

Geometry Management

108
Lecture 31. Tk Widgets

5.7 Tk Widget- All Tkinter widgets have access to specific geometry management methods, which have the purpose
of organizing widgets throughout the parent widget area. Tkinter exposes the following geometry manager classes:
pack, grid, and place.
● The pack() Method− This geometry manager organizes widgets in blocks before placing them in the parent
widget.
● The grid() Method − This geometry manager organizes widgets in a table-like structure in the parent widget.
● The place() Method − This geometry manager organizes widgets by placing them in a specific position in the
parent widget (absolute positions).
WIDGETS

Label

● from tkinter import *


● root = Tk()
● var = StringVar()
● label = Label( root, textvariable = var, relief = RAISED )
● var.set("Hey!? How are you doing?")
● label.pack()
● root.mainloop()
● OUTPUT

ENTRY
● from tkinter import *
● top = Tk()
● L1 = Label(top, text = "User Name")
● L1.pack( side = LEFT)
● E1 = Entry(top, bd = 5)
● E1.pack(side = RIGHT)
● top.mainloop()

Output:

button
● # Code to demonstrate a button
● import Tkinter as tk
109
● root=tk.Tk()
● l=tk.Label(root,text="name",fg="red",bg="lightgreen")
● l.grid(row=0,column=0)
● e=tk.Entry(root)
● e.grid(row=0,column=1)
● b=tk.Button(root,text="click",fg="red",bg="blue")
● b.grid(row=1,column=1)
● root.mainloop()

OUTPUT

-Lecture 32. Tkinter example

CheckButton
from tkinter import *
import tkinter
top = Tk()
CheckVar1 =
IntVar() CheckVar2
= IntVar() def
show():
print(CheckVar1.get()
)
print(CheckVar2.get()
)

C1 = Checkbutton(top, text = "Music", variable = CheckVar1,


\onvalue = 5, offvalue = 0, height=5, \
width = 20, )
C2 = Checkbutton(top, text = "Video", variable = CheckVar2,
\ onvalue = 6, offvalue = 0, height=5, \
width = 20)
B1=Button(top,text="show",command=show)

C1.pack()
C2.pack()
B1.pack()
top.mainloop()

OUTPUT

110
Radiobutton (int as well as string)
from tkinter import *
def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)
root = Tk()
var = IntVar()
R1 = Radiobutton(root, text = "Option 1", variable = var, value = 1,command =
sel)R1.pack( )
R2 = Radiobutton(root, text = "Option 2", variable = var, value = 2, command =
sel) R2.pack( )
R3 = Radiobutton(root, text = "Option 3", variable = var, value = 3, command =
sel) R3.pack( )
label =
Label(root)
label.pack()
root.mainloop()
OUTPUT

111
MessageBox (Showinfo)
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("300x100")
def hello():
messagebox.showinfo("Say Hello", "Hello World")

B1 = Button(top, text = "Say Hello", command = hello)


B1.place(x = 35,y = 50)
top.mainloop()
OUTPUT:-

Frame
from tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
redbutton = Button(frame, text = "Red", fg = "red")
redbutton.pack( side = LEFT)
greenbutton = Button(frame, text = "Brown", fg="brown")
greenbutton.pack( side = LEFT )
bluebutton = Button(frame, text = "Blue", fg = "blue")
bluebutton.pack( side = LEFT )
blackbutton = Button(bottomframe, text = "Black", fg = "black")
blackbutton.pack( side = BOTTOM)
root.mainloop()

OUTPUT:-

112
Lecture 33. Python Programming with IDE

5.8 Python Programming with IDE- An integrated development environment (IDE) refers to a software
application that offers computer programmers with extensive software development abilities. IDEs most often
consist of a source code editor, build automation tools, and a debugger. Most modern IDEs have
intelligent code completion. In this article, you will discover the best Python IDEs currently available and present
in the market.

What Is an IDE?
 An IDE enables programmers to combine the different aspects of writing a computer program.

 IDEs increase programmer productivity by introducing features like editing source code, building executables,
and debugging.

IDE vs. Code Editor: What's the Difference?

 An Integrated Development Environment (IDE) is a software application that provides tools and resources to
help developers write and debug code. An IDE typically includes

A source code editor

A compiler or interpreter

An integrated debugger

A graphical user interface (GUI)

 A code editor is a text editor program designed specifically for editing source code. It typically includes features
that help in code development, such as syntax highlighting, code completion, and debugging.

 The main difference between an IDE and a code editor is that an IDE has a graphical user interface (GUI) while
a code editor does not. An IDE also has features such as code completion, syntax highlighting, and debugging,
which are not found in a code editor.

 Code editors are generally simpler than IDEs, as they do not include many other IDE components. As such,
code editors are typically used by experienced developers who prefer to configure their development environment
manually.

Top Python IDEs

i. IDLE

ii. PyCharm

iii. Visual Studio Code

iv. Jupyter

Important Questions CO-5


i. What is the significance of module in Python? What are the methods of importing a module? Explain with
113
suitable example (2021-22)
ii. Design a calculator with the following buttons and functionalities like addition, subtraction, multiplication,
division and clear. (2023-24 odd sem)

iii. Construct a program to read cities.csv dataset, remove last column and save it in an array. Save the last column
to another array. Plot the first two columns.(2023-24 odd sem)
iv. Construct a plot for following dataset using matplotlib : .(2023-24 odd sem)

v. Describe how to generate random numbers using NumPy. Write a python program to create an array of 5
random integers between 10 and 50. .(2023-24 even sem)

114

You might also like