Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 26

UNIT-3

Data Structure:

Data Structures are a way of organizing data so that it can be accessed


more efficiently depending upon the situation. Data Structures are
fundamentals of any programming language around which a program is built.
Python helps to learn the fundamental of these data structures in a simpler
way as compared to other programming languages.

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:

[1, 2, 'Python', 'Program', 15.9]


['Amy', 'Ryan', 'Henry', 'Emma']
Characteristics of Lists
The characteristics of the List are as follows:

o The lists are in order.


o The list element can be accessed via the index.
o The mutable type of List is
o The rundowns are changeable sorts.
o The number of various elements can be stored in a list.

Updating List Values


Due to their mutability and the slice and assignment operator's ability to update their
values, lists are Python's most adaptable data structure. Python's append() and
insert() methods can also add values to a list.

Consider the following example to update the values inside the List.

Code

1. # updating list values


2. list = [1, 2, 3, 4, 5, 6]
3. print(list)
4. # It will assign value to the value to the second index
5. list[2] = 10
6. print(list)

Output:

[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]

Insert Element in List


list1 = [1, 5, 7, 9, 3]

print(list1)

list1.insert(2,6)

print(list1)
Output:

[1, 5, 7, 9, 3]

[1, 5, 6, 7, 9, 3]

Delete an element in List:

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.

A dictionary is a collection which is ordered*, changeable and do not allow


duplicates.

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}

Finding length of Dictionary

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.

1. import the Tkinter module.


2. Create the main application window.
3. Add the widgets like labels, buttons, frames, etc. to the window.
4. Call the main event loop so that the actions can take place on the user's computer
screen.

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.

3 Checkbutton The Checkbutton is used to display the CheckButton 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.

9 Menu It is used to add 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.

12 Scale It is used to provide the slider to the user.

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.

14 Toplevel It is used to create a separate window container.

15 Spinbox It is an entry widget used to select from options of values.

16 PanedWindow It is like a container widget that contains horizontal or vertical panes.

17 LabelFrame A LabelFrame is a container widget that acts as the container

18 MessageBox This module is used to display the message-box in the desktop based applications.

Python Tkinter Geometry


The Tkinter geometry specifies the method by using which, the widgets are
represented on display. The python Tkinter provides the following geometry
methods.

1. The pack() method


2. The grid() method
3. The place() method

Let's discuss each one of them in detail.

Python Tkinter pack() method


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.

However, the controls are less and widgets are generally added in the less organized
manner.

The syntax to use the pack() is given below.

syntax

1. widget.pack(options)

A list of possible options that can be passed in pack() is given below.

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:

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

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:

Python Tkinter place() method


The place() geometry manager organizes the widgets to the specific x and y
coordinates.
Syntax

1. widget.place(options)

A list of possible options is given below.

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.

One of the most popular databases is MySQL.

MySQL Database
To be able to experiment with the code examples in this tutorial, you should
have MySQL installed on your computer.

You can download a MySQL database


at https://www.mysql.com/downloads/.

Install MySQL Driver


Python needs a MySQL driver to access the MySQL database.

In this tutorial we will use the driver "MySQL Connector".

We recommend that you use PIP to install "MySQL Connector".

PIP is most likely already installed in your Python environment.

Navigate your command line to the location of PIP, and type the following:

Download and install "MySQL Connector":

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\
Scripts>python -m pip install mysql-connector-python

Now you have downloaded and installed a MySQL driver.

Test MySQL Connector


To test if the installation was successful, or if you already have "MySQL
Connector" installed, create a Python page with the following content:

demo_mysql_test.py:

import mysql.connector

If the above code was executed with no errors, "MySQL Connector" is


installed and ready to be used.

Create Connection
Start by creating a connection to the database.

Use the username and password from your MySQL database:

demo_mysql_connection.py:

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)

print(mydb)

Create Table

The SQL CREATE TABLE Statement


The CREATE TABLE statement is used to create a new table in a database.

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

SQL CREATE TABLE Example


The following example creates a table called "Persons" that contains five
columns: PersonID, LastName, FirstName, Address, and City:

Example
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

The PersonID column is of type int and will hold an integer.

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.

The empty "Persons" table will now look like this:

PersonID LastName FirstName Address

Tip: The empty "Persons" table can now be filled with data with the
SQL INSERT INTO statement.

Python MySQL Insert Into Table


Insert Into Table
To fill a table in MySQL, use the "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()

sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"


val = ("John", "Highway 21")
mycursor.execute(sql, val)

mydb.commit()

print(mycursor.rowcount, "record inserted.")

Important!: Notice the statement: mydb.commit(). It is required to make the


changes, otherwise no changes are made to the table.

Select From a Table


To select from a table in MySQL, use the "SELECT" statement:

ExampleGet your own Python Server


Select all records from the "customers" table, and display the result:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("SELECT * FROM customers")

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

sql = "DELETE FROM customers WHERE address = 'Mountain 21'"

mycursor.execute(sql)
mydb.commit()

print(mycursor.rowcount, "record(s) deleted")

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

sql = "UPDATE customers SET address = 'Canyon 123' WHERE address =


'Valley 345'"

mycursor.execute(sql)

mydb.commit()

print(mycursor.rowcount, "record(s) affected")

Commit & RollBack Operation in Python




Python’s commit() method and rollback() method are among the various methods
used for making database transactions. Database transactions are necessary as they
ensure the atomicity, consistency, isolation and durability of the database.
In this article, we will focus on the use of commit() and rollback() method in detail.

1. The commit() method:


The commit() method is used to make sure the changes made to the database are
consistent. It basically provides the database confirmation regarding the changes made
by a user or an application in the database.
Syntax:
comm.commit() #comm refers to the database connection object
For a better understanding of the concept look into the code below followed by the
code explanation. The below demonstration of the commit() method is performed on a
MySQL database.
Example:
Program to update the age of a student named Rishi Kumar and commit it to the
database.
MySQL Table in use:

 Python3

# Python program to demonstrate

# commit() method

import mysql.connector
# Connecting to the Database

mydb = mysql.connector.connect(

host ='localhost',

database ='College',

user ='root',

cs = mydb.cursor()

# drop clause

statement ="UPDATE STUDENT SET AGE = 23 WHERE Name ='Rishi Kumar'"

cs.execute(statement)

# commit changes to the database

mydb.commit()

# Disconnecting from the database

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

# Python program to demonstrate

# rollback() method

import mysql.connector

from mysql.connector import Error

from mysql.connector import errorcode

try:

# Connecting to the Database

mydb = mysql.connector.connect(
host ='localhost',

database ='College',

user ='root',

cs = mydb.cursor()

# drop clause

statement ="UPDATE STUDENT SET AGE = 23 WHERE Name ='Rishi Kumar'"

cs.execute(statement)

# commit changes to the database

mydb.commit()

# update successful message

print("Database Updated !")

except mysql.connector.Error as error :


# update failed message as an error

print("Database Update Failed !: {}".format(error))

# reverting changes because of exception

mydb.rollback()

# Disconnecting from the database

mydb.close()

Output:
If the database transaction is successful the output will be,
Database updated

Network Programming in Python


Python plays an essential role in network programming. The standard library of
Python has full support for network protocols, encoding, and decoding of data and
other networking concepts, and it is simpler to write network programs in Python
than that of C++.

Here, we will learn about the essence of network programming concerning Python.
But for this, the programmer must have basic knowledge of:

 Low-Level Programming using sockets


 Data encoding
 HTTP and web-programming
 High-Level client modules
 Basic networking terms and their concepts etc.

Client and Server model


o A client and server networking model is a model in which computers such as
servers provide the network services to the other computers such as clients to
perform a user based tasks. This model is known as client-server networking
model.
o The application programs using the client-server model should follow the
given below strategies:

o An application program is known as a client program, running on the local


machine that requests for a service from an application program known as a
server program, running on the remote machine.
o A client program runs only when it requests for a service from the server while
the server program runs all time as it does not know when its service is
required.
o A server provides a service for many clients not just for a single client.
Therefore, we can say that client-server follows the many-to-one relationship.
Many clients can use the service of one server.
o Services are required frequently, and many users have a specific client-server
application program. For example, the client-server application program
allows the user to access the files, send e-mail, and so on. If the services are
more customized, then we should have one generic application program that
allows the user to access the services available on the remote computer.

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.

Advantages of Client-server networks:

o Centralized: Centralized back-up is possible in client-server networks, i.e., all


the data is stored in a server.
o Security: These networks are more secure as all the shared resources are
centrally administered.
o Performance: The use of the dedicated server increases the speed of sharing
resources. This increases the performance of the overall system.
o Scalability: We can increase the number of clients and servers separately, i.e.,
the new element can be added, or we can add a new node in a network at any
time.

Date and Time

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

time.sleep(5) # Sleep for 5 seconds

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

# Your code to be timed

for _ in range(1000000):

pass

end_time = time.time()

execution_time = end_time - start_time

print(f"Execution time: {execution_time} seconds")

Getting Current Date and Time

The datetime module provides the datetime class, which you can use to work with dates
and times.

from datetime import datetime

current_datetime = datetime.now()

print("Current Date and Time:", current_datetime)


Formatting Dates

You can format dates using the strftime method. Here's an example:

formatted_date = current_datetime.strftime("%Y-%m-%d %H:%M:%S")

print("Formatted Date:", formatted_date)

You might also like