UNIT-3 Python-1
UNIT-3 Python-1
Data Structure:
Python List
In Python, the sequence of various data types is stored in a list. A list is a collection of
different kinds of values or items. Since Python lists are mutable, we can change their
elements after forming. The comma (,) and the square brackets [enclose the List's
items] serve as separators.
Although six Python data types can hold sequences, the List is the most common and
reliable form. A list, a type of sequence data, is used to store the collection of data.
Tuples and Strings are two similar data formats for sequences.
Lists written in Python are identical to dynamically scaled arrays defined in other
languages, such as Array List in Java and Vector in C++. A list is a collection of items
separated by commas and denoted by the symbol [].
List Declaration
Code
1. # a simple list
2. list1 = [1, 2, "Python", "Program", 15.9]
3. list2 = ["Amy", "Ryan", "Henry", "Emma"]
4.
5. # printing the list
6. print(list1)
7. print(list2)
Output:
Consider the following example to update the values inside the List.
Code
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
print(list1)
list1.insert(2,6)
print(list1)
Output:
[1, 5, 7, 9, 3]
[1, 5, 6, 7, 9, 3]
list1 = [1, 5, 7, 9, 3]
print(list1)
list1.remove(7)
print(list1)
output:
[1, 5, 7, 9, 3]
[1, 5, 9, 3]
Dictionary
Dictionaries are used to store data values in key:value pairs.
Dictionaries are written with curly brackets, and have keys and values:
Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
print(len(thisdict))
Output:
Tkinter
Python provides the standard library Tkinter for creating the graphical user interface
for desktop based applications.
Developing desktop based applications with python Tkinter is not a complex task. An
empty Tkinter top-level window can be created by using the following steps.
Example
1. # !/usr/bin/python3
2. from tkinter import *
3. #creating the application main window.
4. top = Tk()
5. #Entering the event main loop
6. top.mainloop()
Output:
Tkinter widgets
There are various widgets like button, canvas, checkbutton, entry, etc. that are used
to build the python GUI applications.
S Widget Description
N
1 Button The Button is used to add various kinds of buttons to the python application.
2 Canvas The canvas widget is used to draw the canvas on the window.
4 Entry The entry widget is used to display the single-line text field to the user. It is comm
used to accept user values.
5 Frame It can be defined as a container to which, another widget can be added and organiz
6 Label A label is a text used to display some message or information about the other widge
7 ListBox The ListBox widget is used to display a list of options to the user.
8 Menubutton The Menubutton is used to display the menu items to the user.
10 Message The Message widget is used to display the message-box to the user.
11 Radiobutton The Radiobutton is different from a checkbutton. Here, the user is provided with va
options and the user can select only one option among them.
13 Scrollbar It provides the scrollbar to the user so that the user can scroll the window up and do
14 Text It is different from Entry because it provides a multi-line text field to the user so tha
user can write the text and edit the text inside it.
18 MessageBox This module is used to display the message-box in the desktop based applications.
However, the controls are less and widgets are generally added in the less organized
manner.
syntax
1. widget.pack(options)
o expand: If the expand is set to true, the widget expands to fill any space.
o Fill: By default, the fill is set to NONE. However, we can set it to X or Y to determine
whether the widget contains any extra space.
o size: it represents the side of the parent to which the widget is to be placed on the
window.
Example
1. # !/usr/bin/python3
2. from tkinter import *
3. parent = Tk()
4. redbutton = Button(parent, text = "Red", fg = "red")
5. redbutton.pack( side = LEFT)
6. greenbutton = Button(parent, text = "Black", fg = "black")
7. greenbutton.pack( side = RIGHT )
8. bluebutton = Button(parent, text = "Blue", fg = "blue")
9. bluebutton.pack( side = TOP )
10. blackbutton = Button(parent, text = "Green", fg = "red")
11. blackbutton.pack( side = BOTTOM)
12. parent.mainloop()
Output:
This is a more organized way to place the widgets to the python application. The
syntax to use the grid() is given below.
Syntax
1. 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
1. # !/usr/bin/python3
2. from tkinter import *
3. parent = Tk()
4. name = Label(parent,text = "Name").grid(row = 0, column = 0)
5. e1 = Entry(parent).grid(row = 0, column = 1)
6. password = Label(parent,text = "Password").grid(row = 1, column = 0)
7. e2 = Entry(parent).grid(row = 1, column = 1)
8. submit = Button(parent, text = "Submit").grid(row = 4, column = 0)
9. parent.mainloop()
Output:
1. widget.place(options)
o Anchor: It represents the exact position of the widget within the container. The
default value (direction) is NW (the upper left corner)
o bordermode: The default value of the border type is INSIDE that refers to ignore the
parent's inside the border. The other option is OUTSIDE.
o height, width: It refers to the height and width in pixels.
o relheight, relwidth: It is represented as the float between 0.0 and 1.0 indicating the
fraction of the parent's height and width.
o relx, rely: It is represented as the float between 0.0 and 1.0 that is the offset in the
horizontal and vertical direction.
o x, y: It refers to the horizontal and vertical offset in the pixels.
Example
1. # !/usr/bin/python3
2. from tkinter import *
3. top = Tk()
4. top.geometry("400x250")
5. name = Label(top, text = "Name").place(x = 30,y = 50)
6. email = Label(top, text = "Email").place(x = 30, y = 90)
7. password = Label(top, text = "Password").place(x = 30, y = 130)
8. e1 = Entry(top).place(x = 80, y = 50)
9. e2 = Entry(top).place(x = 80, y = 90)
10. e3 = Entry(top).place(x = 95, y = 130)
11. top.mainloop()
Output:
Python MySQL
Python can be used in database applications.
MySQL Database
To be able to experiment with the code examples in this tutorial, you should
have MySQL installed on your computer.
Navigate your command line to the location of PIP, and type the following:
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\
Scripts>python -m pip install mysql-connector-python
demo_mysql_test.py:
import mysql.connector
Create Connection
Start by creating a connection to the database.
demo_mysql_connection.py:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
print(mydb)
Create Table
Syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
The column parameters specify the names of the columns of the table.
The datatype parameter specifies the type of data the column can hold (e.g.
varchar, integer, date, etc.).
Example
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
The LastName, FirstName, Address, and City columns are of type varchar
and will hold characters, and the maximum length for these fields is 255
characters.
Tip: The empty "Persons" table can now be filled with data with the
SQL INSERT INTO statement.
Example
Insert a record in the "customers" table:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mydb.commit()
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Delete Record
You can delete records from an existing table by using the "DELETE FROM"
statement:
Example
Delete any record where the address is "Mountain 21":
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql)
mydb.commit()
Update Table
You can update existing records in a table by using the "UPDATE" statement:
Example
Overwrite the address column from "Valley 345" to "Canyon 123":
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql)
mydb.commit()
Python3
# commit() method
import mysql.connector
# Connecting to the Database
mydb = mysql.connector.connect(
host ='localhost',
database ='College',
user ='root',
cs = mydb.cursor()
# drop clause
cs.execute(statement)
mydb.commit()
mydb.close()
Output:
2. The rollback() method:
The rollback() method is used to revert the last changes made to the database. If a
condition arises where one is not satisfied with the changes made to the database or a
database transaction fails, the rollback() method can be used to retrieve the original
data that was changed through the commit() method.
Syntax:
comm.rollback() #comm refers to the database connection object
The below code shows the use of rollback() method to revert changes if a database
transaction fails:
Python3
# rollback() method
import mysql.connector
try:
mydb = mysql.connector.connect(
host ='localhost',
database ='College',
user ='root',
cs = mydb.cursor()
# drop clause
cs.execute(statement)
mydb.commit()
mydb.rollback()
mydb.close()
Output:
If the database transaction is successful the output will be,
Database updated
Here, we will learn about the essence of network programming concerning Python.
But for this, the programmer must have basic knowledge of:
Client
A client is a program that runs on the local machine requesting service from the
server. A client program is a finite program means that the service started by the user
and terminates when the service is completed.
Server
A server is a program that runs on the remote machine providing services to the
clients. When the client requests for a service, then the server opens the door for the
incoming requests, but it never initiates the service.
A server program is an infinite program means that when it starts, it runs infinitely
unless the problem arises. The server waits for the incoming requests from the
clients. When the request arrives at the server, then it responds to the request.
Sleep: If you want to introduce a delay in your program, you can use the sleep function
from the time module.
import time
print("Before sleep")
print("After sleep")
Program Execution Time:
To measure the execution time of a piece of code, you can use the time module. Here's an
example using the time module:
import time
start_time = time.time()
for _ in range(1000000):
pass
end_time = time.time()
The datetime module provides the datetime class, which you can use to work with dates
and times.
current_datetime = datetime.now()
You can format dates using the strftime method. Here's an example: