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

Python II notes

The document provides an overview of arrays in Python, including how to create, access, and manipulate them using the array module. It also introduces NumPy, a powerful library for numerical data processing, highlighting its advantages over Python lists and its role in data science. Additionally, it covers the basics of the Pandas library for data manipulation and analysis, explaining its key features and data structures like Series and DataFrame.

Uploaded by

vinaykavinayka7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python II notes

The document provides an overview of arrays in Python, including how to create, access, and manipulate them using the array module. It also introduces NumPy, a powerful library for numerical data processing, highlighting its advantages over Python lists and its role in data science. Additionally, it covers the basics of the Pandas library for data manipulation and analysis, explaining its key features and data structures like Series and DataFrame.

Uploaded by

vinaykavinayka7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

ARRAY

An array is a collection of items stored at contiguous memory locations.


The idea is to store multiple items of the same type together.
This makes it easier to calculate the position of each element by simply adding an offset
to a base value, i.e., the memory location of the first element of the array (generally
denoted by the name of the array).

Create an Array in Python


Array in Python can be created by importing an array
module. array( data_type , value_list ) is used to create array in Python with data type
and value list specified in its arguments.
import array as arr

a = arr.array('i', [1, 2, 3])


print("The new created array is : ", end=" ")
for i in range(0, 3):
print(a[i], end=" ")
print()
b = arr.array('d', [2.5, 3.2, 3.3])
print("\nThe new created array is : ", end=" ")
for i in range(0, 3):
print(b[i], end=" ")
Adding Elements to an Array
Elements can be added to the Python Array by using built-in insert() function.
Insert is used to insert one or more data elements into an array.
Based on the requirement, a new element can be added at the beginning, end, or any
given index of array.
append() is also used to add the value mentioned in its arguments at the end of the
Python array.
Accessing Elements from the Array
In order to access the array items refer to the index number.
Use the index operator [ ] to access an item in a array in Python.
The index must be an integer.
import array as arr
a = arr.array('i', [1, 2, 3, 4, 5, 6])
print("Access element is: ", a[0])
print("Access element is: ", a[3])
b = arr.array('d', [2.5, 3.2, 3.3])
print("Access element is: ", b[1])
print("Access element is: ", b[2])

[Date] 1
Removing Elements from the Array
Elements can be removed from the Python array by using built-in remove() function but
an Error arises if element doesn’t exist in the set. remove() method only removes one
element at a time,
to remove range of elements, iterator is used. pop() function can also be used to remove
and return an element from the array, by default it removes only the last element of the
array, to remove element from a specific position of the array, index of the element is
passed as an argument to the pop() method.
import array
arr = array.array('i', [1, 2, 3, 1, 5])
print("The new created array is : ", end="")
for i in range(0, 5):
print(arr[i], end=" ")
print("\r")
print("The popped element is : ", end="")
print(arr.pop(2))
print("The array after popping is : ", end="")
for i in range(0, 4):
print(arr[i], end=" ")
print("\r")
arr.remove(1)
print("The array after removing is : ", end="")
for i in range(0, 3):
print(arr[i], end=" ")

NumPy (Numerical Python)


is an open source Python library that’s used in almost every field of science and
engineering.
It’s the universal standard for working with numerical data in Python, and it’s at the core
of the scientific Python and PyData ecosystems.
NumPy users include everyone from beginning coders to experienced researchers doing
state-of-the-art scientific and industrial research and development.
The NumPy API is used extensively in Pandas, SciPy, Matplotlib, scikit-learn, scikit-
image and most other data science and scientific Python packages.
What is NumPy?
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.
NumPy was created in 2005 by Travis Oliphant. It is an open source project and you can
use it freely.
NumPy stands for Numerical Python.
The NumPy library contains multidimensional array and matrix data structures. It
provides ndarray, a homogeneous n-dimensional array object, with methods to efficiently
operate on it.
NumPy can be used to perform a wide variety of mathematical operations on arrays.

[Date] 2
It adds powerful data structures to Python that guarantee efficient calculations with arrays
and matrices and it supplies an enormous library of high-level mathematical functions
that operate on these arrays and matrices.

What’s the difference between a Python list and a NumPy array?


NumPy gives you an enormous range of fast and efficient ways of creating arrays and
manipulating numerical data inside them.
While a Python list can contain different data types within a single list,
all of the elements in a NumPy array should be homogeneous. The mathematical
operations that are meant to be performed on arrays would be extremely inefficient if the
arrays weren’t homogeneous

[Date] 3
Why use NumPy?
 NumPy arrays are faster and more compact than Python lists.
 An array consumes less memory and is convenient to use.
 NumPy uses much less memory to store data and it provides a mechanism of
specifying the data types.
 This allows the code to be optimized even further.
What is an array?
 An array is a central data structure of the NumPy library.
 An array is a grid of values and
 it contains information about the raw data,
 how to locate an element, and
 ow to interpret an element.
 It has a grid of elements that can be indexed in various ways.
 The elements are all of the same type, referred to as the array dtype.
 An array can be indexed
 by a tuple of nonnegative integers,
 by booleans,
 by another array, or by integers.
 The rank of the array is the number of dimensions.
 The shape of the array is a tuple of integers giving the size of the array along each
dimension.
 The array object in NumPy is called ndarray, it provides a lot of supporting
functions that make working with ndarray very easy.
 Arrays are very frequently used in data science, where speed and resources are very
important.

Why is NumPy Faster Than Lists?

[Date] 4
1. NumPy arrays are stored at one continuous place in memory unlike lists, so
processes can access and manipulate them very efficiently.
2. This behavior is called locality of reference in computer science.
3. This is the main reason why NumPy is faster than lists. Also it is optimized to work
with latest CPU architectures.
4. Which Language is NumPy written in?
5. NumPy is a Python library and is written partially in Python, but most of the parts
that require fast computation are written in C or C++.
Where is the NumPy Codebase?
The source code for NumPy is located at this github repository
https://github.com/numpy/numpy
github: enables many people to work on the same codebase.
Printing an array
import numpy
arr = numpy.array([1, 2, 3, 4, 5])
print(arr)\

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
We can create a NumPy ndarray object by using the array() function.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(type(arr))
Arrays in Phython
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: an array referred to as a “ndarray,”
which is shorthand for
“N-dimensional array.”
An N-dimensional array is simply an array with any number of dimensions. We can have
 1-D, or one-dimensional array,
 2-D, or two-dimensional array, and so on.
The NumPy ndarray class is used to represent both matrices and vectors.
A vector is an array with a single dimension (there’s no difference between row and
column vectors),
while a matrix refers to an array with two dimensions.
For 3-D or higher dimensional arrays, the term tensor is also commonly used.
In NumPy, dimensions are called axes. This means that if you have a 2D array that looks
like this:
[[0., 0., 0.],
[1., 1., 1.]]
array has 2 axes.
The first axis has a length of 2 and
the second axis has a length of 3.
Operations using NumPy:

[Date] 5
• Using NumPy, a developer can perform the following operations −
• Mathematical and logical operations on arrays.
• Fourier transforms and routines for shape manipulation.
• Operations related to linear algebra. NumPy has in-built functions for linear algebra
and random number generation.

0-D Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.
Example
Create a 0-D array with value 42
import numpy as np

arr = np.array(42)

print(arr)

1-D Arrays
An array that has 0-D arrays as its elements is 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
arr = np.array([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. These are often used to
represent matrix or 2nd order tensors. NumPy has a whole sub module dedicated towards
matrix operations called numpy.mat
Example: :reate 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)

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:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)

Python program to demonstrate basic array characteristics


import numpy as np
# Creating array object
arr = np.array( [[ 1, 2, 3],
[ 4, 2, 5]] )

[Date] 6
# Printing type of arr object
print("Array is of type: ", type(arr))

# Printing array dimensions (axes)


print("No. of dimensions: ", arr.ndim)
# Printing shape of array
print("Shape of array: ", arr.shape)

# Printing size (total number of elements) of array


print("Size of array: ", arr.size)

# Printing type of elements in array


print("Array stores elements of type: ", arr.dtype)
Array is of type: <class 'numpy.ndarray'>
No. of dimensions: 2
Shape of array: (2, 3)
Size of array: 6
Array stores elements of type: int64

Operations on single array: We can use overloaded arithmetic operators to do element-


wise operation on array to create a new array. In case of +=, -=, *= operators, the existing
array is modified.
Python program to demonstrate basic operations on single array
import numpy as np

a = np.array([1, 2, 5, 3])

# add 1 to every element


print ("Adding 1 to every element:", a+1)

# subtract 3 from each element


print ("Subtracting 3 from each element:", a-3)

# multiply each element by 10


print ("Multiplying each element by 10:", a*10)

# square each element


print ("Squaring each element:", a**2)

# modify existing array


a *= 2
print ("Doubled each element of original array:", a)

# transpose of array
a = np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]])

[Date] 7
print ("\nOriginal array:\n", a)
print ("Transpose of array:\n", a.T)

Unary operators: Many unary operations are provided as a method of ndarray class.
This includes sum, min, max, etc. These functions can also be applied row-wise or
column-wise by setting an axis parameter.
# Python program to demonstrate
# unary operators in numpy
import numpy as np

arr = np.array([[1, 5, 6],


[4, 7, 2],
[3, 1, 9]])

# maximum element of array


print ("Largest element is:", arr.max())
print ("Row-wise maximum elements:",
arr.max(axis = 1))
# minimum element of array
print ("Column-wise minimum elements:",
arr.min(axis = 0))
# sum of array elements
print ("Sum of all array elements:",
arr.sum())

PANDAS
Pandas is a Python library used for working with data sets. It has functions for analyzing,
cleaning, exploring, and manipulating data.
The name "Pandas" has a reference to both "Panel Data", and "Python Data Analysis" and
was created by Wes McKinney in 2008.
Pandas is an open-source library that is made mainly for working with relational or
labeled data both easily and intuitively. It provides various data structures and operations
for manipulating numerical data and time series. This library is built on top of the NumPy
library.

[Date] 8
Why Use Pandas?
Pandas allows us to analyze big data and make conclusions based on statistical theories.
Pandas can clean messy data sets, and make them readable and relevant.
Relevant data is very important in data science.

What Can Pandas Do?

Pandas gives you answers about the data. Like:


Is there a correlation between two or more columns?
What is average value?
Max value?
Min value?
Key Features of Pandas
It has a fast and efficient DataFrame object with the default and customized indexing.
Used for reshaping and pivoting of the data sets. Group by data for aggregations and
transformations.
It is used for data alignment and integration of the missing data.
Provide the functionality of Time Series. Process a variety of data sets in different
formats like matrix data, tabular heterogeneous, time series. Handle multiple operations
of the data sets such as subsetting, slicing, filtering, groupBy, re-ordering, and re-shaping.
It integrates with the other libraries such as SciPy, and scikit-learn.
Provides fast performance, and If you want to speed it, even more, you can use
the Cython.
Python Pandas Data Structure
Series
It is defined as a one-dimensional array that is capable of storing various data types. The
row labels of series are called the index. We can easily convert the list, tuple, and
dictionary into series using "series' method. A Series cannot contain multiple columns. It
has one parameter:
Data: It can be any list, dictionary, or scalar value.
Creating Series from Array:
Before creating a Series, Firstly, we have to import the numpy module and then use
array() function in the program.
import pandas as pd
import numpy as np

[Date] 9
info = np.array(['P','a','n','d','a','s'])
a = pd.Series(info)
print(a)

import pandas as pd
import numpy as np

# Creating empty series


ser = pd.Series()
print(ser)

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

DataFrame
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular
data structure with labeled axes (rows and columns). A Data frame is a two-dimensional
data structure, i.e., data is aligned in a tabular fashion in rows and columns. Pandas
DataFrame consists of three principal components, the data, rows, and columns.

[Date] 10
Creating a DataFrame:
In the real world, a Pandas DataFrame will be created by loading the datasets from
existing storage, storage can be SQL Database, CSV file, an Excel file. Pandas
DataFrame can be created from the lists, dictionary, and from a list of dictionaries, etc.
Create a DataFrame using List:
We can easily create a DataFrame in Pandas using list.
import pandas as pd
# a list of strings
x = ['Python', 'Pandas']

# Calling DataFrame constructor on list


df = pd.DataFrame(x)
print(df)

import pandas as pd
# Calling DataFrame constructor
df = pd.DataFrame()
print(df)

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

[Date] 11
# Calling DataFrame constructor on list
df = pd.DataFrame(lst)
print(df)

Create a simple Pandas DataFrame:


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)

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
Return row 0:
#refer to the row index:
print(df.loc[0])

[Date] 12
Example
Return row 0 and 1:
#use a list of indexes:
print(df.loc[[0, 1]])

Named Indexes
With the index argument, you can name your own indexes.
Add a list of names to give each row a name:
import pandas as pd
data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}
df = pd.DataFrame(data, index = ["day1", "day2", "day3"])
print(df)

Load Files Into a DataFrame


Load a comma separated file (CSV file) into a DataFrame:
import pandas as pd

df = pd.read_csv('data.csv')

print(df)
If you have a large DataFrame with many rows, Pandas will only return the first 5 rows,
and the last 5 rows
Increase the maximum number of rows to display the entire DataFrame:

[Date] 13
import pandas as pd
pd.options.display.max_rows = 9999
df = pd.read_csv('data.csv')
print(df)

df.read_csv('file_name.csv’) # relative position


df.read_csv('C:/Users/abc/Desktop/file_name.csv')

From excel sheet


import pandas as pd

# Import the excel file and call it xls_file


excel_file = pd.ExcelFile('pandasEx.xlsx')

# View the excel_file's sheet names


print(excel_file.sheet_names)

# Load the excel_file's Sheet1 as a dataframe


df = excel_file.parse('Sheet1')
print(df)
display only 5 rows using nrows parameter
df = pd.read_csv('example1.csv',
header=0,
index_col=["tip", "sex"],
usecols=["tip", "sex", "time"],
nrows=5)

Print(pdf)

[Date] 14
skiprows help to skip some rows in CSV, i.e, here you will observe that the upper row
and the last row from the original CSV data have been skipped.
pd.read_csv("example1.csv", skiprows = [1,12])
df.tail(2)
df.head(2)
Data Visualization

Data visualization is the practice of translating information into a visual context, such as a
map or graph, to make data easier for the human brain to understand and pull insights
from. The main goal of data visualization is to make it easier to identify patterns, trends
and outliers in large data sets. The term is often used interchangeably with others,
including information graphics, information visualization and statistical graphics.

Why is data visualization important?


Data visualization provides a quick and effective way to communicate information in a
universal manner using visual information. The practice can also help businesses identify
which factors affect customer behavior; pinpoint areas that need to be improved or need
more attention; make data more memorable for stakeholders; understand when and where
to place specific products; and predict sales volumes.

Other benefits of data visualization include the following:


the ability to absorb information quickly, improve insights and make faster decisions;

an increased understanding of the next steps that must be taken to improve the
organization;

an improved ability to maintain the audience's interest with information they can
understand;

an easy distribution of information that increases the opportunity to share insights with
everyone involved;

eliminate the need for data scientists since data is more accessible and understandable;
and

an increased ability to act on findings quickly and, therefore, achieve success with greater
speed and less mistakes.

Matplotlib

Matplotlib is a low level graph plotting library in python that serves as a visualization
utility.

[Date] 15
Matplotlib was created by John D. Hunter.

Matplotlib is open source and we can use it freely.

Matplotlib is mostly written in python, a few segments are written in C, Objective-C and
Javascript for Platform compatibility.

Version

import matplotlib

print(matplotlib.__version__)

Pyplot

Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported
under the plt alias:

import matplotlib.pyplot as plt

Python Program to illustrate data visualization

Or

Explain Data visualization

MATPLOTLIB
import matplotlib.pyplot as plt
import numpy as np
x1=np.linspace(0,5,10)
y1=x1**2
plt.plot(x1,y1)
plt.title("days squared chart")
plt.xlabel("days")
plt.ylabel("days squared")

x=[5,2,9,4,7]

[Date] 16
y=[10,6,8,4,2]
plt.bar(x,y)

x=[5,2,9,4,7]
y=[10,6,8,4,2]
plt.scatter(x,y)

x=[5,2,9,4,7]
y=[10,6,8,4,2]
plt.hist(y)

cars=['Audi', 'bmw', 'ford', 'tesla', 'jaguar', 'mercedes']


data=[23,17,35,29,12,41]
fig=plt.figure(figsize=(10,7))
plt.pie(data, labels=cars)
plt.show()

[Date] 17
import pandas as pd
df=pd.DataFrame(np.random.rand(10,5), columns=['A','B','C','D','E'])
df.plot.area()
plt.show()

days=[1,2,3,4,5]
sleeping=[7,8,6,11,7]
eating=[2,3,4,3,2]
working=[7,8,7,2,2]
playing=[7,8,7,8,3]
plt.plot([1,2,3,4,5],[7,8,6,11,7], color='m', label='sleeping', linewidth=5)
plt.plot([1,2,3,4,5],[2,3,4,3,2], color='r', label='eating', linewidth=5)
plt.plot([1,2,3,4,5],[7,8,7,2,2], color='c', label='playing', linewidth=5)

#box plot
df=pd.DataFrame(np.random.rand(10,5),columns=['A','B','C','D','E'])
df.plot.box()
plt.show

[Date] 18
SQLite,
The Python programming language has powerful features for database programming.
Python is a high-level, general-purpose, and very popular programming language.
Basically, it was designed with an emphasis on code readability, and programmers can
express their concepts in fewer lines of code.
We can also use Python with SQL.
The diagram given below illustrates how a connection request is sent to MySQL
connector Python, how it gets accepted from the database and how the cursor is executed
with result data.
Python supports various databases like SQLite, MySQL, Oracle, Sybase, PostgreSQL,
etc.

Python also supports


Data Definition Language (DDL),
Data Manipulation Language (DML) and Data Query Statements. T
The Python standard for database interfaces is the Python SQLite,
The following steps will allow you to easily set up your Python SQL Server Integration:
Step 1: Establish the SQL Server Connection
Step 2: Run an SQL Query
Step 3: Extract Query Results to Python
Step 4: Apply Modifications in SQL Server
What is SQLite
SQLite is an embedded SQL (Structured Query Language) database engine library that
works with many languages.According to the official website, SQL text is compiled into
bytecode, which is then run by a virtual machine. Therefore, it is extremely fast and can
efficiently handle complex queries.
A SQLite database is stored as a disk file, similar to a CSV (comma-separated values)
file. But SQLite has many advantages over using a CSV file:
It is written using C. C is a statically-typed, compiled language which is much faster than
most languages, including Python.
It’s lightweight, so it performs better and faster than reading from a CSV file.
It’s easy to set up
It can handle more complex queries.
It’s more useful to learn, in case you are ever tasked with using SQL or MySQL in the
future.
SQLite is a C-language library that implements a SQL database engine that is relatively
1. quick,

[Date] 19
2. serverless, and
3. self-contained,
4. high-reliable.
SQLite is the most commonly used database engine in the test environment (Refer to
SQLite Home page).

How to Connect to SQLite Database in Python


1. import sqlite3 module
2. Use the connect() method
3. Use the cursor() method
4. Use the execute() method
5. Extract result using fetchall()
6. Close cursor and connection objects
7. Catch database exception
import sqlite3 statement imports the sqlite3 module in the program. Using the classes and
methods defined in the sqlite3 module we can communicate with the SQLite database.
Use the connect() method of the connector class with the database name. To establish a
connection to SQLite, you need to pass the database name you want to connect. If you
specify the database file name that already presents on the disk, it will connect to it. But if
your specified SQLite database file doesn’t exist, SQLite creates a new database for you.
Use the cursor() method
Use the cursor() method of a connection class to create a cursor object to execute SQLite
command/queries from Python.
The execute() methods run the SQL query and return the result.
Use cursor.fetchall() or fetchone() or fetchmany() to read query result.
use cursor.clsoe() and connection.clsoe() method to close the cursor and SQLite
connections after your work completes
use cursor.clsoe() and connection.clsoe() method to close the cursor and SQLite
connections after your work completes
Catch database exception if any that may occur during this connection process.
Operations That can be performed on a database using sqlite:
1. Create: Use the INSERT statement to add new records to the database
2. Read: Use the SELECT statement to retrieve data from the database
3. Update: Use the UPDATE statement to modify existing records
4. Delete: Use the DELETE statement to remove records
5. DROP: Use the DROP statement to remove Table

Connect To Database
Following Python code shows how to connect to an existing database. If the database
does not exist, then it will be created and finally a database object will be returned.
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";

[Date] 20
Create a Table
Following Python program will be used to create a table in the previously created
database.
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
conn.execute('''CREATE TABLE COMPANY (ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL);''')
print "Table created successfully";
conn.close()
When the above program is executed, it will create the COMPANY table in your test.db
and it will display the following messages −
Opened database successfully
Table created successfully
Insert Operation
Following Python program shows how to create records in the COMPANY table created
in the above example.
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (1, 'Paul', 32, 'California', 20000.00 )");
conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (2, 'Allen', 25, 'Texas', 15000.00 )");
conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (3, 'Teddy', 23, 'Norway', 20000.00 )");
conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 )");
conn.commit()
print "Records created successfully";
conn.close()
When the above program is executed, it will create the given records in the COMPANY
table and it will display the following two lines −
Opened database successfully
Records created successfully

Select Operation
Following Python program shows how to fetch and display records from the COMPANY
table created in the above example.

[Date] 21
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
cursor = conn.execute("SELECT id, name, address, salary from COMPANY")
for row in cursor:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"
print "Operation done successfully";
conn.close()
When the above program is executed, it will produce the following result
.
Opened database successfully
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 20000.0

ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000.0

ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0

ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0

Operation done successfully


Update Operation
Following Python code shows how to use UPDATE statement to update any record and
then fetch and display the updated records from the COMPANY table.
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
conn.execute("UPDATE COMPANY set SALARY = 25000.00 where ID = 1")
conn.commit
print "Total number of rows updated :", conn.total_changes

[Date] 22
cursor = conn.execute("SELECT id, name, address, salary from COMPANY")
for row in cursor:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"
print "Operation done successfully";
conn.close()
When the above program is executed, it will produce the following result.
Opened database successfully
Total number of rows updated : 1
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 25000.0

ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000.0

ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0

ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0
Operation done successfully

Delete Operation
Following Python code shows how to use DELETE statement to delete any record and
then fetch and display the remaining records from the COMPANY table.
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
conn.execute("DELETE from COMPANY where ID = 2;")
conn.commit()
print "Total number of rows deleted :", conn.total_changes
cursor = conn.execute("SELECT id, name, address, salary from COMPANY")
for row in cursor:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"

[Date] 23
print "Operation done successfully";
conn.close()

When the above program is executed, it will produce the following result.
Opened database successfully
Total number of rows deleted : 1
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 20000.0

ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0

ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0
Dropping a table
• import sqlite3
• #Connecting to sqlite
• conn = sqlite3.connect('example.db') #Creating a cursor object using the cursor()
method cursor = conn.cursor()
• #Doping EMPLOYEE table if already exists cursor.execute("DROP TABLE emp")
print("Table dropped... ")
• #Commit your changes in the database conn.commit()
• #Closing the connection
conn.close()

TKinter

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 with tkinter is the fastest and
easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task.

To create a tkinter app:

Importing the module – tkinter

Create the main window (container)

Add any number of widgets to the main window

[Date] 24
Apply the event Trigger on the widgets.

#!/usr/bin/python import Tkinter

top = Tkinter.Tk()

# Code to add widgets will go here... top.mainloop()

There are two main methods used which the user needs to remember while creating
the Python application with GUI.

1.Tk(screenName=None, baseName=None, className=’Tk’, useTk=1):

To create a main window, tkinter offers a method ‘Tk(screenName=None,


baseName=None, className=’Tk’, useTk=1)’. To change the name of the window, you
can change the className to the desired one. The basic code used to create the main
window of the application is:m=tkinter.Tk() where m is the name of the main window
object

2. mainloop():

There is a method known by the name mainloop() is used when your application is ready
to run. mainloop() is an infinite loop used to run the application, wait for an event to
occur and process the event as long as the window is not closed.

Layout Management

tkinter also offers access to the geometric configuration of the widgets which can
organize the widgets in the parent windows. There are mainly three geometry manager or
layout manager classes class.

pack() method:It organizes the widgets in blocks before placing in the parent widget.

grid() method:It organizes the widgets in grid (table-like structure) before placing in the
parent widget.

[Date] 25
place() method:It organizes the widgets by placing them on specific positions directed
by the programmer.

Layout management Pack()

This geometry manager organizes widgets in blocks before placing them in the parent
widget.

Syntax

widget.pack( pack_options )

Here is the list of possible options −

expand − When set to true, widget expands to fill any space not otherwise used in
widget's parent.

fill − Determines whether widget fills any extra space allocated to it by the packer, or
keeps its own minimal dimensions: NONE (default), X (fill only horizontally), Y (fill
only vertically), or BOTH (fill both horizontally and vertically).

side − Determines which side of the parent widget packs against: TOP (default),
BOTTOM, LEFT, or RIGHT.

Grid()

This geometry manager organizes widgets in a table-like structure in the parent widget.

Syntax

widget.grid( grid_options ) Here is the list of possible options −

column − The column to put widget in; default 0 (leftmost column).

[Date] 26
columnspan − How many columns widgetoccupies; default 1.

ipadx, ipady − How many pixels to pad widget, horizontally and vertically, inside
widget's borders.

padx, pady − How many pixels to pad widget, horizontally and vertically, outside v's
borders.

row − The row to put widget in; default the first row that is still empty.

rowspan − How many rowswidget occupies; default 1.

sticky − What to do if the cell is larger than widget. By default, with sticky='', widget is
centered in its cell. sticky may be the string concatenation of zero or more of N, E, S, W,
NE, NW, SE, and SW, compass directions indicating the sides and corners of the cell to
which widget sticks.

Place()

This

geometry manager organizes widgets by placing them in a specific position in the parent
widget.

Syntax

widget.place( place_options )

Here is the list of possible options −

anchor − The exact spot of widget other options refer to: may be N, E, S, W, NE, NW,
SE, or SW, compass directions indicating the corners and sides of widget; default is NW
(the upper left corner of widget)

[Date] 27
bordermode − INSIDE (the default) to indicate that other options refer to the parent's
inside (ignoring the parent's border); OUTSIDE otherwise.

height, width − Height and width in pixels.

relheight, relwidth − Height and width as a float between 0.0 and 1.0, as a fraction of the
height and width of the parent widget.

relx, rely − Horizontal and vertical offset as a float between 0.0 and 1.0, as a fraction of
the height and width of the parent widget.

x, y − Horizontal and vertical offset in pixels.

Widgets

Button:To add a button in your application, this widget is used.


The general syntax is:

w=Button(master, option=value)

master is the parameter used to represent the parent window.

There are number of options which are used to change the format of the Buttons. Number
of options can be passed as parameters separated by commas. Some of them are listed
below.

activebackground: to set the background color when button is under the cursor.

activeforeground: to set the foreground color when button is under the cursor.

bg: to set the normal background color.

command: to call a function.

font: to set the font on the button label.

[Date] 28
image: to set the image on the button.

width: to set the width of the button.

height: to set the height of the button.

Sample Program

import tkinter as tk

r = tk.Tk()

r.title('Counting Seconds')

button = tk.Button(r, text='Stop', width=25, command=r.destroy)

button.pack()

r.mainloop()

Canvas: It is used to draw pictures and other complex layout like graphics, text and
widgets.
The general syntax is:

w = Canvas(master, option=value)

master is the parameter used to represent the parent window.There are number of options
which are used to change the format of the widget.

Number of options can be passed as parameters separated by commas. Some of them are
listed below.

bd: to set the border width in pixels.

bg: to set the normal background color.

cursor: to set the cursor used in the canvas.

[Date] 29
highlightcolor: to set the color shown in the focus highlight.

width: to set the width of the widget.

height: to set the height of the widget.

Sample Program

from tkinter import *

master = Tk()

w = Canvas(master, width=40, height=60)

w.pack()

canvas_height=20

canvas_width=200

y = int(canvas_height / 2)

w.create_line(0, y, canvas_width, y )

mainloop()

CheckButton: To select any number of options by displaying a number of options to a


user as toggle buttons.

The general syntax is:

w = CheckButton(master, option=value)

There are number of options which are used to change the format of this widget.

Number of options can be passed as parameters separated by commas. Some of them are
listed below.

Title: To set the title of the widget.

activebackground: to set the background color when widget is under the cursor.

activeforeground: to set the foreground color when widget is under the cursor.

bg: to set the normal background color.

[Date] 30
command: to call a function.

font: to set the font on the button label.

image: to set the image on the widget.

Sample Program

from tkinter import *

master = Tk()

var1 = IntVar()

Checkbutton(master, text='male', variable=var1).grid(row=0, sticky=W)

var2 = IntVar()

Checkbutton(master, text='female', variable=var2).grid(row=1, sticky=W)

mainloop()

Entry:It is used to input the single line text entry from the user.. For multi-line text input,
Text widget is used.
The general syntax is:w=Entry(master, option=value) master is the parameter used to
represent the parent window.
There are number of options which are used to change the format of the widget.

Number of options can be passed as parameters separated by commas. Some of them are
listed below.

bd: to set the border width in pixels.

bg: to set the normal background color.

cursor: to set the cursor used.

command: to call a function.

highlightcolor: to set the color shown in the focus highlight.

width: to set the width of the button.

height: to set the height of the button.

[Date] 31
Sample Program

from tkinter import *

master = Tk()

Label(master, text='First Name').grid(row=0)

Label(master, text='Last Name').grid(row=1)

e1 = Entry(master)

e2 = Entry(master)

e1.grid(row=0, column=1)

e2.grid(row=1, column=1)

mainloop()

Frame: It acts as a container to hold the widgets. It is used for grouping and organizing
the widgets.

The general syntax is:

w = Frame(master, option=value)

master is the parameter used to represent the parent window.There are number of options
which are used to change the format of the widget.

Number of options can be passed as parameters separated by commas. Some of them are
listed below.

highlightcolor: To set the color of the focus highlight when widget has to be focused.

bd: to set the border width in pixels.

bg: to set the normal background color.

cursor: to set the cursor used.

width: to set the width of the widget.

height: to set the height of the widget

[Date] 32
Sample Program

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()

Label: It refers to the display box where you can put any text or image which can be
updated any time as per the code.
The general syntax is:

w=Label(master, option=value)

master is the parameter used to represent the parent window.There are number of options
which are used to change the format of the widget.

[Date] 33
Number of options can be passed as parameters separated by commas. Some of them are
listed below.

bg: to set the normal background color.

bg to set the normal background color.

command: to call a function.

font: to set the font on the button label.

image: to set the image on the button.

width: to set the width of the button.

height” to set the height of the button.

Sample Program

from tkinter import *

root = Tk()

w = Label(root, text='GeeksForGeeks.org!')

w.pack()

root.mainloop()

7.Listbox: It offers a list to the user from which the user can accept any number of
options.
The general syntax is:

w = Listbox(master, option=value)

master is the parameter used to represent the parent window.There are number of options
which are used to change the format of the widget.

Number of options can be passed as parameters separated by commas. Some of them are
listed below.

highlightcolor: To set the color of the focus highlight when widget has to be focused.

[Date] 34
bg: to set the normal background color.

bd: to set the border width in pixels.

font: to set the font on the button label.

image: to set the image on the widget.

width: to set the width of the widget.

height: to set the height of the widget.

Sample Program

from tkinter import *

top = Tk()

Lb = Listbox(top)

Lb.insert(1, 'Python')

Lb.insert(2, 'Java')

Lb.insert(3, 'C++')

Lb.insert(4, 'Any other')

Lb.pack()

top.mainloop()

MenuButton: It is a part of top-down menu which stays on the window all the time.
Every menubutton has its own functionality.

The general syntax is:

w = MenuButton(master, option=value)

master is the parameter used to represent the parent window.There are number of options
which are used to change the format of the widget.

Number of options can be passed as parameters separated by commas. Some of them are
listed below.

[Date] 35
activebackground: To set the background when mouse is over the widget.

activeforeground: To set the foreground when mouse is over the widget.

bg: to set the normal background color.

bd: to set the size of border around the indicator.

cursor: To appear the cursor when the mouse over the menubutton.

image: to set the image on the widget.

width: to set the width of the widget.

height: to set the height of the widget.

highlightcolor: To set the color of the focus highlight when widget has to be focused.

Sample Program

from tkinter import *

top = Tk()

mb = Menubutton ( top, text = "GfG")

mb.grid()

mb.menu = Menu ( mb, tearoff = 0 )

mb["menu"] = mb.menu

cVar = IntVar()

aVar = IntVar()

mb.menu.add_checkbutton ( label ='Contact', variable = cVar )

mb.menu.add_checkbutton ( label = 'About', variable = aVar )

mb.pack()

top.mainloop()

[Date] 36
Menu: It is used to create all kinds of menus used by the application.
The general syntax is:

w = Menu(master, option=value)

master is the parameter used to represent the parent window.There are number of options
which are used to change the format of this widget.

Number of options can be passed as parameters separated by commas. Some of them are
listed below.

title: To set the title of the widget.

activebackground: to set the background color when widget is under the cursor.

activeforeground: to set the foreground color when widget is under the cursor.

bg: to set the normal background color.

command: to call a function.

font: to set the font on the button label.

image: to set the image on the widget.

Sample Program

from tkinter import *

root = Tk()

menu = Menu(root)

root.config(menu=menu)

filemenu = Menu(menu)

menu.add_cascade(label='File', menu=filemenu)

filemenu.add_command(label='New')

filemenu.add_command(label='Open...')

filemenu.add_separator()

filemenu.add_command(label='Exit', command=root.quit)

helpmenu = Menu(menu)

menu.add_cascade(label='Help', menu=helpmenu)

helpmenu.add_command(label='About')

[Date] 37
mainloop()

Message: It refers to the multi-line and non-editable text. It works same as that of Label.
The general syntax is:

w = Message(master, option=value)

master is the parameter used to represent the parent window. There are number of options
which are used to change the format of the widget.

Number of options can be passed as parameters separated by commas. Some of them are
listed below.

bd: to set the border around the indicator.

bg: to set the normal background color.

font: to set the font on the button label.

image: to set the image on the widget.

width: to set the width of the widget.

height: to set the height of the widget

Sample Program

from tkinter import *

main = Tk()

ourMessage ='This is our Message'

messageVar = Message(main, text = ourMessage)

messageVar.config(bg='lightgreen')

messageVar.pack( )

main.mainloop( )

[Date] 38
RadioButton: It is used to offer multi-choice option to the user. It offers several options
to the user and the user has to choose one option.
The general syntax is:

w = RadioButton(master, option=value)

There are number of options which are used to change the format of this widget.

Number of options can be passed as parameters separated by commas. Some of them are
listed below.

activebackground: to set the background color when widget is under the cursor.

activeforeground: to set the foreground color when widget is under the cursor.

bg: to set the normal background color.

command: to call a function.

font: to set the font on the button label.

image: to set the image on the widget.

width: to set the width of the label in characters.

height: to set the height of the label in characters.

Sample Program

from tkinter import *

root = Tk()

v = IntVar()

Radiobutton(root, text='GfG', variable=v, value=1).pack(anchor=W)

Radiobutton(root, text='MIT', variable=v, value=2).pack(anchor=W)

mainloop()

[Date] 39
Scale: It is used to provide a graphical slider that allows to select any value from that
scale. The general syntax is:

w = Scale(master, option=value)

master is the parameter used to represent the parent window.

Number of options can be passed as parameters separated by commas. Some of them are
listed below.

cursor: To change the cursor pattern when the mouse is over the widget.

activebackground: To set the background of the widget when mouse is over the widget.

bg: to set the normal background color.

orient: Set it to HORIZONTAL or VERTICAL according to the requirement.

from_: To set the value of one end of the scale range.

to: To set the value of the other end of the scale range.

image: to set the image on the widget.

width: to set the width of the widget.

Scrollbar: It refers to the slide controller which will be used to implement listed widgets.
The general syntax is:

w = Scrollbar(master, option=value)

master is hte parameter used to represent the parent window.

Number of options can be passed as parameters separated by commas. Some of them are
listed below.

width: to set the width of the widget.

activebackground: To set the background when mouse is over the widget.

bg: to set the normal background color.

bd: to set the size of border around the indicator.

[Date] 40
cursor: To appear the cursor when the mouse over the menubutton.

Text: To edit a multi-line text and format the way it has to be displayed.
The general syntax is:

w =Text(master, option=value) There are number of options which are used to change the
format of the text. Number of options can be passed as parameters separated by commas.
Some of them are listed below.

highlightcolor: To set the color of the focus highlight when widget has to be focused.

insertbackground: To set the background of the widget.

bg: to set the normal background color.

font: to set the font on the button label.

image: to set the image on the widget.

width: to set the width of the widget.

height: to set the height of the widget.

TopLevel: This widget is directly controlled by the window manager. It don’t need any
parent window to work on.The general syntax is:

w = TopLevel(master, option=value)

There are number of options which are used to change the format of the widget. Number
of options can be passed as parameters separated by commas. Some of them are listed
below.

bg: to set the normal background color.

bd: to set the size of border around the indicator.

cursor: To appear the cursor when the mouse over the menubutton.

width: to set the width of the widget.

height: to set the height of the widget.

SpinBox: It is an entry of ‘Entry’ widget. Here, value can be input by selecting a fixed
value of numbers.The general syntax is:

w = SpinBox(master, option=value) There are number of options which are used to


change the format of the widget. Number of options can be passed as parameters
separated by commas. Some of them are listed below.

bg: to set the normal background color.

[Date] 41
bd: to set the size of border around the indicator.

cursor: To appear the cursor when the mouse over the menubutton.

command: To call a function.

width: to set the width of the widget.

activebackground: To set the background when mouse is over the widget.

disabledbackground: To disable the background when mouse is over the widget.

from_: To set the value of one end of the range.

to: To set the value of the other end of the range.

PannedWindow:It is a container widget which is used to handle number of panes


arranged in it. The general syntax is:

w = PannedWindow(master, option=value)

master is the parameter used to represent the parent window.


There are number of options which are used to change the format of the widget. Number
of options can be passed as parameters separated by commas. Some of them are listed
below.

bg: to set the normal background color.

bd: to set the size of border around the indicator.

cursor: To appear the cursor when the mouse over the menubutton.

width: to set the width of the widget.

height: to set the height of the widget.

[Date] 42

You might also like