Python UNIT5 Notes
Python UNIT5 Notes
PROGRAMMING
UNIT - 5
The tkinter Module
Python offers multiple options for developing GUI (Graphical User Interface). Out
of all the GUI methods, tkinter is the most commonly used method. It is a
standard Python interface to the Tk GUI toolkit shipped with Python.
Python tkinter is the fastest and easiest way to create GUI applications. Creating a
GUI using tkinter is an easy task.
Cursor
# Create a cursor object using the cursor() method
cursor = conn.cursor()
Execute
# Create table
cursor.execute('''CREATE TABLE IF NOT EXISTS stocks
(date text, trans text, symbol text, qty real, price real)'‘’)
# Insert a row of data
cursor.execute("INSERT INTO stocks VALUES ('2006-01-
05','BUY','RHAT',100,35.14)")
Commit
# Save (commit) the changes
conn.commit()
Close
# Close the connection
conn.close()
Connect to Database
Connecting to the SQLite Database can be established using the connect()
method, passing the name of the database to be accessed as a parameter. If
that database does not exist, then it’ll be created.
sqliteConnection = sqlite3.connect('sql.db’)
But what if you want to execute some queries after the connection is being
made. For that, a cursor has to be created using the cursor() method on the
connection instance, which will execute our SQL queries.
cursor = sqliteConnection.cursor()
print('DB Init')
Create Table
Syntax:
CREATE TABLE database_name.table_name(
column1 datatype PRIMARY KEY(one or more columns),
column2 datatype,
column3 datatype,
…..
columnN datatype
);
Steps to Create a Table:
Import the required module
Establish the connection or create a connection object with the database using
the connect() function of the sqlite3 module.
Create a Cursor object by calling the cursor() method of the Connection object.
Form table using the CREATE TABLE statement with the execute() method of the
Cursor class.
Example:
import sqlite3
# Connecting to sqlite
# connection object
connection_obj = sqlite3.connect('geek.db')
# cursor object
cursor_obj = connection_obj.cursor()
# Drop the GEEK table if already exists.
cursor_obj.execute("DROP TABLE IF EXISTS GEEK")
# Creating table
table = """ CREATE TABLE GEEK (
Email VARCHAR(255) NOT NULL,
First_Name CHAR(25) NOT NULL,
Last_Name CHAR(25),
Score INT
); """
cursor_obj.execute(table)
print("Table is Ready")
# Close the connection
connection_obj.close()
Operations on Tables
INSERT - The SQL INSERT INTO statement of SQL is used to insert a new row in a
table.
SELECT - This statement is used to retrieve data from an SQLite table and this
returns the data contained in the table.
UPDATE - The UPDATE statement in SQL is used to update the data of an existing
table in the database. We can update single columns as well as multiple columns
using UPDATE statement as per our requirement.
DELETE - SQLite database we use the DELETE statement to delete data from a table.
DROP - DROP is used to delete the entire database or a table. It deleted both
records in the table along with the table structure.
Operations on Tables – Insert Records
Syntax:
INSERT INTO table_name VALUES (value1, value2, value3,…);
table_name: name of the table.
value1, value2,.. : value of first column, second column,… for the new record
Example:
# Creating table
table ="""CREATE TABLE STUDENT(NAME VARCHAR(255), CLASS VARCHAR(255),
SECTION VARCHAR(255));"""
cursor.execute(table)
# Queries to INSERT records.
cursor.execute('''INSERT INTO STUDENT VALUES ('Raju', '7th', 'A')''')
Operations on Tables – Select Records
Syntax:
SELECT * FROM table_name;
* : means all the column from the table
To select specific column replace * with the column name or column names.
Syntax:
cursor.fetchall()
where, cursor is an object of sqlite3 connection with database.
To fetch all records we will use fetchall() method.
Operations on Tables – Select Records
Example:
statement = '''SELECT * FROM GEEK'''
cursor_obj.execute(statement)
output = cursor_obj.fetchall()
for row in output:
print(row)
connection_obj.commit()
# Close the connection
connection_obj.close()
Operations on Tables – Update Records
Syntax:
UPDATE table_name SET column1 = value1, column2 = value2,…
WHERE condition;
Example:
# Updating Data
cursor.execute('''UPDATE EMPLOYEE SET INCOME = 5000 WHERE Age<25;''')
print('\nAfter Updating...\n')
# Display data
print("EMPLOYEE Table: ")
data = cursor.execute('''SELECT * FROM EMPLOYEE''')
for row in data:
print(row)
Operations on Tables – Delete Records
Syntax:
DELETE FROM table_name [WHERE Clause]
Example:
#delete data
cursor_obj.execute("DELETE FROM STUDENT WHERE Score < 15")
connection_obj.commit()
# Close the connection
connection_obj.close()
Operations on Tables – Drop Records
Syntax:
DROP TABLE TABLE_NAME;
Example:
# drop table
connection.execute("DROP TABLE STUDENT ") #student is the tablename
print("data dropped successfully")
import numpy as np
arr = np.array((1, 2, 3, 4, 5))
print(arr)
Operations on Arrays
Note: These are operations on NumPy Arrays, Array & NumPy Arrays are
different.
print('\nSecond array:')
arr2 = np.array([12, 12])
print(arr2)
[22 20]
[-2 -4]
print('\nAdding the two arrays:')
0.83333333 0.66666667
If nothing else is specified, the values are labeled with their index number. First
value has index 0, second value has index 1 etc. This label can be used to access
a specified value.
print(myvar[0])
Series - Lables
With the index argument, you can name your own labels.
Example:
import pandas as pd
a = [1, 7, 2]
myvar = pd.Series(a, index = ["x", "y", "z"])
print(myvar)
When you have created labels, you can access an item by referring to the label.
print(myvar["y"])
DataFrames
A Pandas DataFrame is a 2 dimensional data structure, like a 2 dimensional
array, or a table with rows and columns.
Example:
import pandas as pd
data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}
#load data into a DataFrame object:
df = pd.DataFrame(data)
print(df)
DataFrames – Locate Row
As you can see from the result above, the DataFrame is like a table with rows
and columns.
Pandas use the loc attribute to return one or more specified row(s)
Example:
#refer to the row index:
print(df.loc[0])
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. Some of the libraries are listed below:
Matplotlib
Seaborn
Bokeh
Matplotlib Library
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, histogram, etc.
Matplotlib provides a lot of flexibility.
To install this type the below command in the terminal.
pip install matplotlib
Different Types of Charts using Pyplot -
Line chart
Line Chart is used to represent a relationship between two data X and Y on a
different axis. It is plotted using the plot() function.
Example:
import matplotlib.pyplot as plt
x=[20,10,40,2,45,67]
y=[10,20,30,40,50,60]
plt.figure(figsize=(8,6))
plt.title("Line Plot Graph",fontsize=15,color='red')
plt.xlabel("X Axis",fontsize=12,color='blue')
Line chart
plt.ylabel("Y Axis",fontsize=12,color='blue')
plt.plot(x,y,color="purple",linewidth=5,label="Line Plot")
plt.legend(loc=1,fontsize=12)
plt.show()
Bar chart
A bar plot or bar chart is a graph that represents the category of data with
rectangular bars with lengths and heights that is proportional to the values which
they represent. It can be created using the bar() method.
Example:
import matplotlib.pyplot as plt
x=[20,10,30,40,2,45,67]
y=[10,25,30,40,50,60,42]
plt.figure(figsize=(8,6))
plt.title("Bar Plot Graph",fontsize=15,color='red')
Bar chart
plt.xlabel("X Axis",fontsize=12,color='blue')
plt.ylabel("Y Axis",fontsize=12,color='blue')
plt.bar(x,y,color="purple",linewidth=5,label="Bar Plot")
plt.legend(loc=1,fontsize=12)
plt.show()
Histogram
A histogram is basically used to represent data in the form of some groups. It is a
type of bar plot where the X-axis represents the bin ranges while the Y-axis gives
information about frequency. The hist() function is used to compute and create a
histogram. In histogram, if we pass categorical data then it will automatically
compute the frequency of that data i.e. how often each value occurred.
Example:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(1) #generates random integers
data=np.random.randint(1,100,50)
plt.title("Histogram Plot",fontsize=15,color="red")
Histogram
plt.xlabel("X Axis",fontsize=12,color="blue")
plt.ylabel("Y Axis",fontsize=12,color="blue")
plt.hist(data)
plt.show()
Pie chart
A Pie Chart is a circular statistical plot that can display only one series of data. The
area of the chart is the total percentage of the given data. Pie charts are commonly
used in business presentations like sales, operations, survey results, resources, etc.
as they provide a quick summary.
Example:
import matplotlib.pyplot as plt
data=[78,90,10,45,35]
lab=["A","B","C","D","E"]
col=["red","orange","blue","green","yellow"]
plt.figure(figsize=(6,6))
plt.title("Pie Plot",fontsize=15,color="red")
plt.pie(data,colors=col,labels=lab,autopct="%.2f%%")
plt.show()