Unit - 5 Python
Unit - 5 Python
GU-INTERFACE
Python Tkinter:
Python provides the standard library Tkinter for creating the graphical user
interface for desktop-based applications.
Example
The pack() widget is used to organize widget in the block. The positions
widgets added to the python application using the pack() method can be
controlled by using the various options specified in the method call.
Example
Output:
Python Tkinter grid() method
The grid() geometry manager organizes the widgets in the tabular form.
We can specify the rows and columns as the options in the method call. We
can also specify the column span (width) or rowspan(height) of a widget.
This is a more organized way to place the widgets to the python application.
The syntax to use the grid() is given below.
Syntax
widget.grid(options)
A list of possible options that can be passed inside the grid() method is
given below.
o Column
The column number in which the widget is to be placed. The leftmost
column is represented by 0.
o Columnspan
The width of the widget. It represents the number of columns up to
which, the column is expanded.
o ipadx, ipady
It represents the number of pixels to pad the widget inside the widget's
border.
o padx, pady
It represents the number of pixels to pad the widget outside the
widget's border.
o row
The row number in which the widget is to be placed. The topmost row
is represented by 0.
o rowspan
The height of the widget, i.e. the number of the row up to which the
widget is expanded.
o Sticky
If the cell is larger than a widget, then sticky is used to specify the
position of the widget inside the cell. It may be the concatenation of
the sticky letters representing the position of the widget. It may be N,
E, W, S, NE, NW, NS, EW, ES.
Example
Output:
Syntax
widget.place(options)
Example
from tkinter import *
top = Tk()
top.geometry("400x250")
name = Label(top, text = "Name").place(x = 30,y = 50)
email = Label(top, text = "Email").place(x = 30, y = 90)
password = Label(top, text = "Password").place(x = 30, y = 130)
e1 = Entry(top).place(x = 80, y = 50)
e2 = Entry(top).place(x = 80, y = 90)
e3 = Entry(top).place(x = 95, y = 130)
top.mainloop()
Output:
Tkinter widgets
There are various widgets like button, canvas, checkbutton, entry, etc. that
are used to build the python GUI applications.
SN Widget Description
Syntax
1. w = canvas(parent, options)
Example
top = Tk()
top.geometry("200x200")
Output:
Python Tkinter Button
The button widget is used to add various types of buttons to the python
application. Python allows us to configure the look of the button according
to our requirements. Various options can be set or reset depending upon
the requirements.
Syntax
W = Button(parent, options)
Example1
#python application to create a simple button
Output:
Example2:
The Checkbutton can contain the text or images. The Checkbutton is mostly
used to provide many choices to the user among which, the user needs to
choose the one. It generally implements many of many selections.
w = checkbutton(master, options)
Example
from tkinter import *
top = Tk()
top.geometry("200x200")
checkvar1 = IntVar()
checkvar2 = IntVar()
checkvar3 = IntVar()
chkbtn1.pack()
chkbtn2.pack()
chkbtn3.pack()
top.mainloop()
Output:
Another example:
Syntax
w = Entry (parent, options)
SN Option Description
1 Bg The background color of the widget.
Example
from tkinter import *
top = Tk()
top.geometry("400x250")
name = Label(top, text = "Name").place(x = 30,y = 50)
email = Label(top, text = "Email").place(x = 30, y = 90)
password = Label(top, text = "Password").place(x = 30, y = 130)
sbmitbtn = Button(top, text = "Submit",activebackground = "pink", active
foreground = "blue").place(x = 30, y = 170)
e1 = Entry(top).place(x = 80, y = 50)
e2 = Entry(top).place(x = 80, y = 90)
e3 = Entry(top).place(x = 95, y = 130)
top.mainloop()
Output:
Python Tkinter Label
The Label is used to specify the container box where we can place the text
or images. This widget is used to provide the message to the user about
other widgets used in the python application.
There are the various options which can be specified to configure the text
or the part of the text shown in the Label.
Syntax
w = Label (master, options)
SN Option Description
1 anchor It specifies the exact position of the text within the size
provided to the widget. The default value is CENTER,
which is used to center the text within the specified
space.
6 font The font type of the text written inside the widget.
Example
#creating label
uname = Label(top, text = "Username").place(x = 30,y = 50)
#creating label
password = Label(top, text = "Password").place(x = 30, y = 90)
sbmitbtn = Button(top, text = "Submit",activebackground = "pink", active
foreground = "blue").place(x = 30, y = 120)
e1 = Entry(top,width = 20).place(x = 100, y = 50)
e2 = Entry(top, width = 20).place(x = 100, y = 90)
top.mainloop()
Output:
Python Tkinter Listbox
The Listbox widget is used to display the list items to the user. We can
place only text items in the Listbox and all text items contain the same font
and color.
The user can choose one or more items from the list depending upon the
configuration.
1. w = Listbox(parent, options)
SN Option Description
3 cursor The mouse pointer will look like the cursor type like
dot, arrow, etc.
Example
from tkinter import *
top = Tk()
top.geometry("200x250")
lbl = Label(top,text = "A list of favourite countries...")
listbox = Listbox(top)
listbox.insert(1,"India")
listbox.insert(2, "USA")
listbox.insert(3, "Japan")
listbox.insert(4, "Austrelia")
lbl.pack()
listbox.pack()
top.mainloop()
Output:
SQLite3
What is SQLite
SQLite is embedded relational database management system. It is self-
contained, serverless, zero configuration and transactional SQL database
engine.
SQLite is different from other SQL databases because unlike most other SQL
databases, SQLite does not have a separate server process. It reads and writes
directly to ordinary disk files. A complete SQL database with multiple tables,
indices, triggers, and views, is contained in a single disk file.
There are several reasons why you might choose to use SQLite in
your project:
1. Ease of use: SQLite is very easy to get started with, as it
requires no setup or configuration. You can simply include
the library in your project and start using it.
2. Embeddability: SQLite is designed to be embedded into
other applications. It is a self-contained, serverless
database engine, which means you can include it in your
application without the need for a separate database
server.
3. Lightweight: SQLite is a very lightweight database
engine, with a small library size (typically less than 1MB).
This makes it well-suited for use in applications where the
database is embedded directly into the application binary,
such as mobile apps.
4. Serverless: As mentioned earlier, SQLite is a serverless
database engine, which means there is no need to set up
and maintain a separate database server process. This
makes it easy to deploy and manage, as there are no
additional dependencies to worry about.
5. Cross-platform: SQLite is available on many platforms,
including Linux, macOS, and Windows, making it a good
choice for cross-platform development.
6. Standalone: SQLite stores all of the data in a single file on
the filesystem, which makes it easy to copy or backup the
database.
7. High reliability: SQLite has been widely tested and used
in production systems for many years, and has a
reputation for being a reliable and robust database engine.
Connect SQLite3 with Python
SQLite Methods
➢ Connect method
➢ Cursor method
➢ Execute method
➢ Close method
Connect method:
Connect method is used to connect with the database if database is
already created otherwise, it will create the new database.
Syntax:
Connection string = sqlite3.connect(‘databasename.db’)
Example:
Conn=sqlite3.connect(‘mydatabase.db’)
Example:
# create a cousor object for select query
cursor = connection.execute("SELECT * from student ")
Execute method:
Syntax:
connection_object.execute(“sql statement”)
Example:
Conn.execute(“create table student(name char,regnumber int)”)
Close method:
Close method is used to close the database connection once the process
is done with database.
Syntax:
Connection_object.close()
Example:
Conn.close()
SQLite Commands
SQLite commands are similar to SQL commands. There are three types of
SQLite commands:
import sqlite3
conn = sqlite3.connect('mydatabase.db')
Create a table
Create a table "student" within the database "mydatabase".
import sqlite3
conn = sqlite3.connect('mydatabase.db')
print ("Opened database successfully")
conn.close()
Insert Records
Insert some records in "student" table.
import sqlite3
conn = sqlite3.connect('mydatabase.db')
print("Opened database successfully")
conn.execute("insert into student values(1001,'Lavanya','Msc')")
conn.execute("insert into student values(1002,'Saritha', 'MA')")
conn.execute("insert into student values(1003,'Meena', 'Msc')")
print("three rows inserted successfully")
conn.commit()
conn.close()
import sqlite3
conn=sqlite3.connect('mydatabase.db')
print("Database opened")
Output:
Database opened
(1001, 'Lavanya', 'Msc')
(1002, 'Saritha', 'MA')
(1003, 'Meena', 'Msc')
import sqlite3
conn=sqlite3.connect('mydatabase.db')
print("opened")
conn.execute("update student set class='MCA' where name='Lavanya'")
Output:
Database opened
(1001, 'Lavanya', 'MCA')
(1002, 'Saritha', 'MA')
(1003, 'Meena', 'Msc')
Data Analysis
Example:
C:\Users\lavanya>pip install numpy
Arrays are very frequently used in data science, where speed and
resources are very important.
Import NumPy
Once NumPy is installed, import it in your applications by adding
the import keyword:
import numpy
Example:
import numpy
myarray = numpy.array([1, 2, 3, 4, 5])
print(myarray)
Output:
[1 2 3 4 5]
NumPy as np
NumPy is usually imported under the np alias.
alias: In Python alias are an alternate name for referring to the same
thing.
Create an alias with the as keyword while importing:
import numpy as np
Example:
import numpy as np
arr = np.array(['apple','banana','mango'])
print(arr)
Output:
['apple' 'banana' 'mango']
1-D Arrays
An array that has 0-D arrays called uni-dimensional or 1-D array.
These are the most common and basic arrays.
Example:
Create a 1-D array containing the values 1,2,3,4,5:
import numpy as np
print(arr)
Traversing 1-D array:
import numpy as np
a=np.array([23,45,67,78])
for i in a:
print(i)
output:
23
45
67
78
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.
NumPy has a whole sub module dedicated towards matrix operations
called numpy.mat
Example
Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
Output:
[[1 2 3]
[4 5 6]]
3-D arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D
array.
These are often used to represent a 3rd order tensor.
Example
Create a 3-D array with two 2-D arrays, both containing two arrays with
the values 1,2,3 and 4,5,6:
Example:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)
Output:
[[[1, 2, 3]
[4, 5, 6]]
[[1, 2, 3]
[4, 5, 6]]]
for i in a:
for j in i:
for z in j:
print(z)
output:
1
2
3
4
5
6
7
8
9
10
15
16
The indexes in NumPy arrays start with 0, meaning that the first element has
index 0, and the second has index 1 etc.
Example:
Get the first element from the following array:
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[0])
print(arr[2])
Output:
1
2
Slicing arrays
Slicing in python means taking elements from one given index to another
given index.
Example:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5])
Output:
[2 3 4 5]
Example:
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr = np.concatenate((arr1, arr2))
print(arr)
Output:
[1 2 3 4 5 6]
Searching Arrays
You can search an array for a certain value, and return the indexes that
get a match.
To search an array, use the where() method.
Example
Find the indexes where the value is 3:
import numpy as np
arr = np.array([1, 2, 3, 4, 3, 5])
x = np.where(arr == 3)
print(x)
Output:
(array([2,4]),)
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.
The NumPy ndarray object has a function called sort(), that will sort a
specified array.
Example:
Sort the array:
import numpy as np
a= np.array([3, 2,1,4,7,5)
print(np.sort(a))
Output:
[1 2 3 4 5 7]
Use the len() method to return the length of an array (the number of
elements in an array).
Example:
import numpy as np
fruits=np.array(["apple", "banana", "mango"])
x = len(fruits)
print(x)
output:
3
Pandas In Python
What is Pandas?
Pandas is a Python library used for working with data sets.
The name "Pandas" has a reference to both "Panel Data", and "Python Data
Analysis" and was created by Wes McKinney in 2008.
Installation of Pandas
if you have Python and PIP already installed on a system, then installation of
Pandas is very easy.
Import Pandas
Once Pandas is installed, import it in your applications by adding
the import keyword:
import pandas
Example:
import pandas
mydataset = {
'names': ["Lavanya", "Bindu", "Indu"],
'age': [31,28,26]
}
myvar = pandas.DataFrame(mydataset)
print(myvar)
Output:
Names age
0 Lavanya 31
1 Bindu 28
2 Indu 25
Pandas as pd
Pandas is usually imported under the pd alias.
alias: In Python alias are an alternate name for referring to the same
thing.
Create an alias with the as keyword while importing:
import pandas as pd
Pandas Series
What is a Series?
A Pandas Series is like a column in a table.
It is a one-dimensional array holding data of any type of value.
Example
Create a simple Pandas Series from a list:
import pandas as pd
a = [1, 3, 4]
myseries = pd.Series(a)
print(myseries)
output:
0 1
1 3
2 4
Dtype:int64
Create Labels
With the index argument, you can name your own labels.
Example
#Create your own labels:
import pandas as pd
ar = [1, 3, 4]
myseries= pd.Series(ar, index = ["a", "b", "c"])
print(myseries)
output:
a 1
b 3
c 4
Dtype:int64
Example
Create a simple Pandas Series from a dictionary:
import pandas as pd
student = {"name":'Lavanya', "class": 'BCA', "age": 31}
data = pd.Series(student)
print(data)
output:
name Lavanya
class BCA
age 31
dtype:object
DataFrames
Data sets in Pandas are usually multi-dimensional tables, called
DataFrames.
Series is like a column, a DataFrame is the whole table.
Example
Create a DataFrame from two Series:
import pandas as pd
data = {
"Names": [‘Lavanya’,’Bindu’,’Indu’],
"age": [31, 28, 25], "Qualification": [‘MCA’,’BE’,’MSc’],
}
myframe = pd.DataFrame(data)
print(myframe)
Output:
Names age Qualification
0 Lavanya 31 MCA
1 Bindu 28 BE
2 Indu 25 MSc
Example:
#Load the CSV into a DataFrame:
import pandas as pd
Dataframe1=pd.read_csv("Book2.CSV")
print(Dataframe1)
Output:
Name regno class address
0 lavanya 1001 BCA Bangaloe
1 bindu 1002 BSC mulbagal
2 indu 1003 Bcom kolar
3 chandu 1004 BA mulbagal
4 vani 1005 BSc mysore
5 divya 1006 BA hydrabad
Required Module
pip install xlrd
print(dataframe1)
Output:
0 regno name class age
1 1001 Bindu BE 28
2 1002 Indu MSC 25
3 1003 Divya BE 22
4 1004 Vani BSC 35
5 1005 Chandu MA 32
Data visualisation
Data visualization provides a good, organized pictorial
representation of the data which makes it easier to understand,
observe, analyze. In this, we will discuss how to visualize data
using Python.
Python provides various libraries that come with different features
for visualizing data. All these libraries come with different features
and can support various types of graphs. In this tutorial, we will be
discussing four such libraries.
• Matplotlib
• Seaborn
• Plotly
Matplotlib
Matplotlib is an easy-to-use, low-level data visualization library that
is built on NumPy arrays. It consists of various plots like scatter plot,
line plot, pie chart, bar chart, histogram, etc. Matplotlib provides a
lot of flexibility.
Installation of Matplotlib
If you have Python and PIP already installed on a system, then
installation of Matplotlib is very easy.
Import Matplotlib
import matplotlib
Pyplot
Most of the Matplotlib utilities lies under the pyplot submodule, and are
usually imported under the plt alias:
import matplotlib.pyplot as plt
plot() method:
Example:
#Draw a line in a diagram from position (0,0) to position (6,250):
plt.plot(xpoints, ypoints)
plt.show()
output:
Matplotlib Line chart
Linestyle
You can use the keyword argument linestyle, or shorter ls, to change the
style of the plotted line:
Example:
Matplotlib Bars
With Pyplot, you can use the bar() function to draw bar graphs:
Output:
Horizantal bar
With Pyplot, you can use the barh() function to draw horizontal bar
graphs:
output:
Bar Width
The bar() takes the keyword argument width to set the width of the bars:
Example:
import numpy as np
x = np.array(["c", "c++", "java", "python"])
y = np.array([3, 6, 8, 10])
plt.barh(x,y,color=”hotpink”,width=0.3)
plt.show()
Output:
plt.pie(y)
plt.show()
output:
Labels
Add labels to the pie chart with the label parameter.
The label parameter must be an array with one label for each wedge:
Example
#A simple pie chart:
import matplotlib.pyplot as plt
import numpy as np
y = np.array([30, 25, 25, 15])
mylabels = ["Python", "Java", "C++", "Cprogram"]
Colors
You can set the color of each wedge with the colors parameter.
The colors parameter, if specified, must be an array with one value for
each wedge:
Example:
import numpy as np
mycolours=["hotpink","yellow","red","green"]
plt.show()
Output: