Programming With Python II
Programming With Python II
(Computer Science)
SEMESTER - II (CBCS)
PROGRAMMING WITH
PYTHON - II
: Vandana Maurya
Asst. Professor,
B. K. Birla College (Autonomous), Kalyan
Unit- I
2. Exception handling 13
3. Regular Expressions 23
Unit - II
Unit - III
[Link]. (Computer Science)
SEMESTER - I (CBCS)
Programming with Python – II
(Credits : 2 Lectures/Week: 3)
Objective:
The objective of this paper is to explore the style of structured
programming to give the idea to the students how programming can be
used for designing real-life applications by reading/writing to files, GUI
programming, interfacing database/networks and various other features.
I
Database connectivity in Python: Installing mysql
connector, accessing connector module module,
using connect, cursor, execute & close functions,
reading single & multiple results of query execution,
executing different types of statements, executing
Unit III 15 L
transactions, understanding exceptions in database
connectivity.
Network connectivity: Socket module, creating
server-client programs, sending email, reading from
URL
Text books:
1. Paul Gries , Jennifer Campbell, Jason Montojo, Practical
Programming: An Introduction to Computer
Science Using Python 3, Pragmatic Bookshelf, 2/E 2014
Additional References:
1. James Payne , Beginning Python: Using Python 2.6 and Python 3,
Wiley India, 2010
2. A. Lukaszewski, MySQL for Python: Database Access Made Easy,
Pact Publisher, 2010
II
UNIT 1
1
PYTHON FILE INPUT- OUTPUT
Unit Structure
1.1 Introduction
1.2 Opening files in python
1.3 Closing files in python
1.4 Write to an existing file
1.5 Create a new file
1.6 Python delete file
1.7 Python directory
1.7.1 Get current directory
1.7.2 Changing directory
1.7.3List directories and files
1.7.4 Making a new directory
1.7.5 Removing directory or file
1.1 INTRODUCTION
Files are named locations on disk to store information. They are used to
permanently store data in a non-volatile memory e.g. hard disk.
Random Access Memory (RAM) is volatile memory means it loses its
data when the computer is turned off, we use files for future use of the
data by permanently storing them.
When we want to read from or write to a file, we need to open it first.
When we have finished our work, it needs to be closed so that the
resources that are attached with the file are freed.
Hence, in Python, a file operation takes place in the following sequence:
1. Open a file
2. Read or write (perform operation)
3. Close the file
1
Programming with Python– II
1.2 OPENING FILES IN PYTHON
Python has a built-in open() function to open a file.
The open() function returns a file object, which has a read() method for
reading the content of the file:
On the other hand, binary mode returns bytes, and this is the mode to
be used when dealing with non-text files like images or executable
files.
Mode Description
2
This is the [Link] file we have Python File Input- Output
Example 1.1
Output:
If the file is located in a different location, you will have to specify the file
path, as follows:
Example 1.2
Output:
3
Programming with Python– II Read Only Parts of the File
By default the read() method returns the whole text, but you can also
specify how many characters you want to return:
Example 1.3Return the 5 first characters of the file
Output:
Read Lines
You can return one line by using the readline() method:
Example 1.4Read one line of the file:
Output:
By calling readline() two times, you can read the two first lines:
Example 1.5Read two lines of the file:
Output:
4
By looping through the lines of the file, we can read the whole file, line by Python File Input- Output
line:
Output:
Output:
Note:
You should always close your files, in some cases, due to buffering,
changes made to a file may not show until you close the file.
5
Programming with Python– II
1.4 WRITE TO AN EXISTING FILE
To write to an existing file, we must add a parameter to
the open() function:
"a" - Append
It will append to the end of the file.
"w" - Write
It will overwrite any existing content.
Example 1.8
Open the file "[Link]" and append content to the file:
Output:
Example 1.9
Open the file "[Link]" and overwrite its content:
Output:
6
1.5 CREATE A NEW FILE Python File Input- Output
To create a new file in Python, use the open() method, with one of the
following parameters:
"x" - Create
It will create a file, returns an error if the file exist.
"a" - Append
It will create a file if the specified file does not exist.
"w" - Write
It will create a file if the specified file does not exist.
Example 1.10 Create a file called "[Link]"
Output:
Result: a new empty file is created!
7
Programming with Python– II Example 1.12Remove the file "[Link]":
Output:
Delete Folder
To delete an entire folder, use the [Link]() method:
Example 1.14Remove the folder "myprograms":
Output:
Output:
Syntax of chdir()
[Link](path)
Parameters:
9
Programming with Python– II Example 1.16
Output:
Output:
10
Example 1.18 Python File Input- Output
Output:
11
Programming with Python– II Example 1.20
Output:
Output:
12
2
EXCEPTION HANDLING
Unit Structure
2.1 Introduction
2.1.1 Syntax error
2.1.2 Exceptions
2.1.3 Built-in Exceptions
2.2 Catching Exceptions
2.3 Catching Specific Exception
2.1 INTRODUCTION
Error in Python can be of two types i.e. Syntax errors and Exceptions.
Errors are the problems in a program due to which the program will stop
the execution.
Example 2.1
13
Programming with Python– II Output:
2.1.2 Exceptions
Exceptions are raised when the program is syntactically correct, but the
code resulted in an error. This error does not stop the execution of the
program; however, it changes the normal flow of the program.
Example 2.2
Output:
14
For example: Exception Handling
Let us consider a program where we have a function A that calls
function B, which in turn calls function [Link] an exception occurs in
function C but is not handled in C, an exception passes to B and then to A.
If it is never handled, an error message is displayed, and program comes to
a sudden unexpected halt.
Note: Exception is the base class for all the exceptions in Python.
Exception Description
15
Programming with Python– II
LookupError Raised when errors raised cant be found.
16
ValueError Raised when there is a wrong value in a Exception Handling
specified data type.
Example:
Let us try to access the array element which doesn’t exist i.e whose index
is out of bound and handle the corresponding exception.
Example2.3
Output:
In the above example,statements that may cause the error are placed
inside the try statement (second print statement in our case).
The second print statement tries to access the fifth element; which is not
there in the list;so it throws an exception. This exception is then caught
by the except statement.
try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
Example2.3Catching specific exception in Python
Output:
18
Exception Handling
Output:
19
Programming with Python– II Output:
Syntax:
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
20
Output: Exception Handling
Example 2.6
Output:
RAISING EXCEPTION
The raise statement allows the programmer to force a specific exception
to [Link] must be either an exception instance or an exception class
(a class that derives from Exception).
Example 2.8
The output of the above code is simply “An exception” but a Runtime
error will also occur at the end due to raise statement in the last line. So,
the output on your command line will look like this:
21
Programming with Python– II Output:
Example 2.9
Raise an error and stop the program if value of x is lower than 0
Output:
Output:
22
3
REGULAR EXPRESSIONS
Unit Structure
3.1 Introduction
3.2 Reg Ex functions
3.3 Metacharacters
3.4 Special sequences
3.5 Sets
3.1 INTRODUCTION
Regular Expression, or aRegEx, is a sequence of characters that forms a
search pattern.
RegEx can be used to check if a string contains the specified search
pattern.
Reg Ex Module
Python has a built-in package called re, which can be used to work with
Regular Expressions.
Import the re module:
Import re
Reg Ex in Python
Once you have importedre module, you can start using regular
expressions:
Example 3.1Search the string to see if it starts with "The" and ends with
"Spain":
23
Programming with Python– II Output:
3.2 REGEXFUNCTIONS
The re module offers a set of functions that allows us to search a string for
a match.
Function Description
Findall Returns a list containing all matches.
Search Returns a Match object if there is a match anywhere in the
string.
Split Returns a list where the string has been split at each match.
Sub Replaces one or many matches with a string.
3.3 METACHARACTERS
Meta characters are characters with a special meaning.
| Either or "falls|stays"
24
[] Square Brackets Regular Expressions
. Dot
Dot(.) symbol matches only a single character except for the newline
character (\n).
For example:
a.b will check for the string that contains any character at the place
of the dot such as acb, acbd, abbb, etc.
It will check if the string contains at least 2 characters.
^ Caret
Caret (^) symbol matches the beginning of the string i.e. checks whether
the string starts with the given character(s) or not.
For example:
^g will check if the string starts with g such asglobe, girl, g, etc.
^ge will check if the string starts with ge such as geeks, geeksandgeek
etc.
$ Dollar
Dollar($) symbol matches the end of the string i.e checks whether the
string ends with the given character(s) or not.
For example :
s$ will check for the string that ends with geeks, ends, s, etc.
25
Programming with Python– II ks$ will check for the string that ends with ks such as geeks,
geeksandgeeks, ks, etc.
| Or
Or symbol works as the or operator meaning it checks whether the
pattern before or after the or symbol is present in the string or not.
For example:
a|b will match any string that contains a or b such as acd, bcd, abcd, etc.
? Question Mark
Question mark(?) checks if the string before the question mark in the
regex occurs at least once or not at all.
For example:
ab?c will be matched for the string ac, acb, dabc but will not be
matched for abbc because there are two b.
Similarly, it will not be matched for abdc because b is not followed
by c.
Star
Star (*) symbol matches zero or more occurrences of the regex preceding
the * symbol.
For example:
ab*c will be matched for the string ac, abc, abbbc, dabc, etc. but will
not be matched for abdc because b is not followed by c.
+ Plus
Plus (+) symbol matches one or more occurrences of the regex preceding
the + symbol.
For example:
ab+c will be matched for the string abc, abbc, dabc, but will not be
matched for ac, abdc because there is no b in ac and d is not followed
by c in abdc.
{m, n} – Braces
Braces matches any repetitions preceding regex from m to n both
inclusive.
26
For example : Regular Expressions
a{2, 4} will be matched for the string aaab, baaaac, gaad, but will not
be matched for strings like abc, bc because there is only one a or no a
in both the cases.
(<regex>) – Group
Group symbol is used to group sub-patterns.
For example :
(a|b)cd will match for strings like acd, abcd, gacd, etc.
27
Programming with Python– II
\w Returns a match where the string contains any "\w"
word characters (characters from a to Z, digits
from 0-9, and the underscore _ character)
3.5 SETS
A set is a set of characters inside a pair of square brackets [] with a special
meaning:
Set Description
[0-5][0-9] Returns a match for any two-digit numbers from 00 and 59.
28
The findall() Function Regular Expressions
The findall() function returns a list containing all matches.
Output:
The list contains the matches in the order they are found.
If no matches are found, an empty list is returned:
Output:
29
Programming with Python– II If there is more than one match, only the first occurrence of the match will
be returned.
Example 3.4 Search for the first white-space character in the string
Output:
Output:
30
Example 3.6 Split at each white-space character Regular Expressions
Output:
Output:
Output:
Output:
Match Object
A Match Object is an object containing information about the search and
the result.
Note:
If there is no match, the value None will be returned, instead of the Match
Object.
Example 3.10 Do a search that will return a Match Object
Output:
The Match object has properties and methods used to retrieve information
about the search, and the result:
.span() - returns a tuple containing the startand end positions of the match.
.string- returns the string passed into the function.
.group()-returns the part of the string where there was a match.
Example 3.11 Print the position (start- and end-position) of the first
match occurrence.
The regular expression looks for any words that starts with an upper case
"S".
32
Regular Expressions
Output:
Output:
Example 3.13 Print the part of the string where there was a match.
The regular expression looks for any words that starts with an upper case
"S":
Output:
33
UNIT-II
4
GUI PROGRAMMING IN PYTHON-I
Unit Structure
4.0 Objective
4.1 Introduction
4.2 What is GUI
4.3 Advantages of GUI
4.4 Introduction to GUI library
4.5 Layout management
4.6 Events and bindings
4.7 Fonts
4.8 Colors
4.9 Summary
4.10 Reference for further reading
4.11 Unit End Exercises
4.0 OBJECTIVE
4.1 INTRODUCTION
The graphical user interface (GUI), developed in the late 1970s by
the Xerox Palo Alto research laboratory and Apple’s Macintosh and
Microsoft’s Windows, was designed.
34
Gui Programming in Python-I
4.3 ADVANTAGES OF GUI
1. GUI is very user-friendly
2. GUI is more attractive and multi-colored.
3. It is much easy than the command-driven interface
4. User can switch easily between tasks on the GUI interface
Disadvantages of GUI:
1. It becomes complex if the user needs to communicate with the
computer directly
2. It is fully based applications require more RAM .
3. GUI uses more processing power compared to other interface types
JPython − JPython is a Python port for Java which gives Python scripts.
Tkinter Programming:
Tkinter is the standard GUI library for Python. Tkinter provides a easy as
well as fast way to create GUI applications. Tkinter provides a powerful
object-oriented interface to the Tk GUI toolkit.
Creating a GUI application using Tkinter you need to do the following
steps −
Import the Tkinter module.
Create the GUI application main window.
Add one or more of the above-mentioned widgets to the GUI application.
Enter the main event loop to take action against each event triggered by
the user.
Importing Tkinter:
How to import Tkinter?
To import the Tkinter, use the import statement and write the
tkinter and create iGts object. Call the Tk() GUI Kit. Call the
mainloop() method from the Tk().
35
Programming with Python– II Example:-
>>> import tkinter as x
>>> a=[Link]()
>>>[Link]()
Output
Fill- The fill option is used to fill any extra space allocated to it by packer.
The fill method has its own minimal dimensions and they are NONE, X
(horizontally), Y (vertically) or Both (Vertical and Horizontal)
Side- It find out which side of the parent widget packs against : TOP ,
BOTTOm, LEFT or RIGHT.
Example-
fromtkinter import *
r = Tk()
[Link]('350x300+120+100')
l1 = Label(r, text="Python", bg="#E74C3C", fg="white").pack(fill=X,
padx=12)
36
l2 = Label(r, text="JAVA", bg="#2ECC71", fg="black").pack(fill=X, Gui Programming in Python-I
padx=12)
l3 = Label(r, text="Database", bg="#F1C40F", fg="white").pack(fill=X,
padx=12)
l4 = Label(r, text="Python GUI", bg="#34495E", fg="white").pack(fill=X,
padx=12, pady=12, side=LEFT)
l5 = Label(r, text="Python Database", bg="#5DADE2",
fg="black").pack(fill=X, padx=12, side=LEFT)
l6 = Label(r, text="Python Networking", bg="#A569BD",
fg="white").pack(fill=X, padx=12, side=LEFT)
listbox = Listbox()
[Link](fill=BOTH, expand=1)
for i in range(10):
[Link](END, str(i))
mainloop()
Output:
Grid method:
Grid method geometry manager is used to organize widgets in a table like
structure in the parent widget.
Syntax:
[Link](options)
There are following option
Column : It is a column to put widget in default 0.
Columnspan : This tells that how many columns widget occupies. The
default value is 1.
Row : it is a row to put widget in. default the first row that is still empty.
Rowspan : it tells how many row widget have occupied, be default is is 1.
Example:
fromtkinter import *
37
Programming with Python– II Label(text="Rollno", width=10).grid(row=0, column=0)
Label(text="Name", width=10).grid(row=0, column=1)
Label(text="Age", width=10).grid(row=0, column=2)
Label(text="1001", width=10).grid(row=1, column=0)
Label(text="Sandeep", width=10).grid(row=1, column=1)
Label(text="18", width=10).grid(row=1, column=2)
Label(text="1003", width=10).grid(row=2, column=0)
Label(text="Sachin", width=10).grid(row=2, column=1)
Label(text="17", width=10).grid(row=2, column=2)
Label(text="1005", width=10).grid(row=3, column=0)
Label(text="Deepak", width=10).grid(row=3, column=1)
Label(text="19", width=10).grid(row=3, column=2)
Label(text="1012", width=10).grid(row=4, column=0)
Label(text="Rajesh", width=10).grid(row=4, column=1)
Label(text="21", width=10).grid(row=4, column=2)
mainloop()
Output:
Place()
The place() method of layout manager organizes widgets in the parent
widget by placing them in a specific position.
Syntax:
[Link](place option)
38
root = Tk() Gui Programming in Python-I
Label(root, text="Rollno is : 1090 ").place(x=10, y=20)
Label(root, text="Name is : Sandeep ").place(x=10, y=60)
Label(root, text="Age : 18 ").place(x=10, y=100)
Label(root, text="DOB : 31 March 2005 ").place(x=10, y=140)
Label(root, text="Location is : Mumbai ").place(x=10, y=180)
Label(root, text="University is : Mumbai University ", bg="red",
fg="white").place(x=10, y=220)
mainloop()
Output:
39
Programming with Python– II handler can be type of button or key used to handle event
Whenever event occurs the handler is called to execute particular function
related to the event.
Example:
fromtkinter import *
defadditon():
res=int([Link]())+int([Link]())
[Link](res)
m = Tk()
mt=StringVar()
Label(m, text="Enter First Number ").grid(row=0, sticky=W)
Label(m, text="Enter Second Number ").grid(row=1, sticky=W)
Label(m, text="Addition is :").grid(row=3, sticky=W)
result=Label(m, text="", textvariable=mt).grid(row=3,column=1,
sticky=W)
n1 = Entry(m)
n2 = Entry(m)
[Link](row=0, column=1)
[Link](row=1, column=1)
b = Button(m, text="Click for Addition", command=additon)
[Link](row=0, column=2,columnspan=2, rowspan=2)
mainloop()
output:
40
Events Gui Programming in Python-I
Tkinter provides a powerful mechanism to deal with events. For each
widget, you can bind python functions and methods to events. If an event
matching the event description occurs in the widget, the given handler is
called with an object describing the event.
The event sequence is given as a string, using the following:
Syntax
(modifier-type-detail)
The type field is the essential part of an event specifier, whereas the
“modifier” and “detail” fields are not obligatory and are left out in many
cases. They are used to provide additional information for the chosen
“type”. The event “type” describes the kind of event to be bound, e.g.
actions like mouse clicks, key presses or the widget got the input focus.
Events and its Description
<buttton> - A mouse button is pressed with the mouse pointer over the
widget. If you press down a mouse button over a widget and keep it
pressed.
<motion> (x,y) - The mouse is moved with a mouse button being held
[Link] current position of the mouse pointer is provided in the x and y
members of the event object passed to the callback, i.e. event.x, event.y
<ButtonRelease>- Event, if a button is released.
The current position of the mouse pointer is provided in the x and y
members of the event object passed to the callback, i.e. event.x, event.y
<Double-Button>- Similar to the Button event, see above, but the button is
double clicked instead of a single click
Class bindings
The bind method we used in the above example creates an instance
binding. This means that the binding applies to a single widget only; if you
create new frames, they will not inherit the bindings.
But Tkinter also allows you to create bindings on the class and application
level
Example:
fromtkinter import *
def function1(event):
print("Single Click on Button ,Button-l")
def function2(event):
41
Programming with Python– II print("Double Click on Button")
import sys; [Link]()
widget = Button(None, text='Mouse Clicks')
[Link]()
[Link]('<Button-1>', function1)
[Link]('<Double-1>', function2)
[Link]()
Output:
4.7 FONTS
The Simple Tuple fonts are commonly use for specify the font. The
tuple contains first element font family, Second element size in points
and third element style modifiers like underline, bold etc.
Example:
(“Arial”,”28”,”bold”
For Font object Fonts
User can create a font object by importing the tkFont and using its font
class constructor.
Import tkFont
Font= [Link](option…)
Option are:
Family – It is the font family name as a string
Size- It is the font height as an integer in points.
42
Weight – it uses “bold” for boldface Gui Programming in Python-I
Underline use 1 for underline, 0 for normal
Example
X=[Link](family=”Arial”, size=14, weight=”bold”)
4.8 COLORS
Standard attributes and properties of Widgets-
There are some common attributes like color, size, and font.
Color:
Color is represented in the string format. User can specify the color in the
following:
Name
User can use any locally defined standard color name like “red”, “green”,
“white”, “black”, “green” etc.
Hexadecimal unit
Instead of color name use hexadecimal digit like ‘#fff’ for white, ‘#00000’
for balck, ‘#000fff000’ for pure green.
Color option
The following color option
activebackground - It is used to set Background color for the active
widget
activeforeground - It is used to set foreground color for the active widget
Background – bg is used to set background color for the active widget
highlightbackground – bg is used to set background color for the highlight
region when the widget has focus.
highlightcolor– It is used to set the foreground color for the highlight
region when the widget has focus.
Selectbackground - It is used to set the background color for the selected
item of the widget.
Selectforeground - It is used to set the foreground color for the selected
item of the widget.
disabledforeground - It is used to set foreground color for the disable
widget
Foreground – fg is used to set foreground color for the active widget
43
Programming with Python– II
4.9 SUMMARY
1. GUI is more attractive and multi-colored.
2. Tkinter is the standard GUI library for Python. Python when combined
with
3. Tkinter provides a fast and easy way to create GUI applications.
Tkinter has three built-in layout managers: the pack , grid , and place
managers.
44
5
GUI PROGRAMMING IN PYTHON-II
Unit Structure
5.0 Objective
5.1 Introduction
5.2 Drawing on canvas:
a. line,
b. oval,
c. rectangle
5.3 Widgets such as :
d. frame,
e. label,
f. button,
g. check button,
h. entry,
i. list box,
j. message,
k. radio button,
l. text,
m. spin box
5.4 Summary
5.5 Reference for further reading
5.6 Unit End Exercises
5.0 OBJECTIVE
Understand canvas, frame, Label
5.1 INTRODUCTION
Graphical user interfaces (GUI) would become the standard of
user-centered design in software application programming, providing
45
Programming with Python– II users to operate computers through the direct manipulation of graphical
icons such as Text box, Buttons, Scroll bars, Spin box etc.
b. oval
The create_oval() method is used to create a circle item. The first
four parameters are the bounding box coordinates of the circle. In other
words, they are x and y coordinates of the top-left and bottom-right points
of the box, in which the circle is drawn.
Example:
fromtkinter import *
t = Tk()
C = Canvas(t, bg="green", height=350, width=400)
coord = 10, 50, 240, 210
46
arc = C.create_oval(10, 10, 350, 200, width=1) Gui Programming in Python-II
[Link]()
[Link]()
output:
c. rectangle
To create a rectangle create_rectangle() method is used.
This method accepts 4 parameters x1, y1, x2, y2. Here x1 and y1 are
the coordinates for the top left corner and x2 and y2 are the
coordinates for the bottom right corner.
Example:
fromtkinter import *
t = Tk()
C = Canvas(t, bg="green", height=350, width=400)
coord = 10, 50, 240, 210
arc = C.create_rectangle(50, 50, 290, 260, width=2)
[Link]()
[Link]()
output:
47
Programming with Python– II 2. Widgets such as :
a. Frame
The frame widget is used to group the widget in a friendly way. Its helps
to look the GUI organized. It is like a container which arranges the
position of the other widget .
Syntax:
F=Frame (master, option)
Example:
fromtkinter import *
root = Tk()
frame = Frame(root)
[Link]()
bottomframe = Frame(root)
[Link]( side = BOTTOM )
button1 = Button(frame, text="Add", fg="green")
[Link]( side = LEFT)
button2 = Button(frame, text="Div", fg="brown")
[Link]( side = LEFT )
button3 = Button(frame, text="Sub", fg="blue")
[Link]( side = LEFT )
button4 = Button(bottomframe, text="Multi", fg="black")
[Link]( side = BOTTOM)
[Link]()
Output:
b. Label
Labels
The label widget is a display box where we can place text or images. We
can change label text any time we want . If we want to underline the text
we can do that and also we can span text across multiple lines
Syntax
Simple syntax to create this widget −
x = Label ( master, option, ... )
The argument master represents the parent window and the argument
option is the option used by label widget as a key-value pairs and they are
separated by comma.
48
Gui Programming in Python-II
The list of most commonly used options for this widget
Example:
importtkinter as tk
r = [Link]()
x = [Link](r, text="Hello Student ")
[Link]()
[Link]()
output
Example 2:
importtkinter as tk
r = [Link]()
[Link](r,
text="Mumbai University",
fg = "red",
font = "Times").pack()
[Link](r,
text="python programming",
fg = "light green",
bg = "dark green",
font = "Helvetica 16 bold italic").pack()
[Link](r,
text="object oriented programming python",
fg = "blue",
bg = "yellow",
font = "Verdana 14 bold").pack()
[Link]()
49
Programming with Python– II Output:
Example:
importtkinter as tk
r = [Link]()
img1 = [Link](file="[Link]")
txt = "Hi, Student "
w = [Link](r, compound = [Link],
text=txt,
image=img1).pack(side="right")
[Link]()
output:
c. Button
Labels
The label widget is a display box where we can place text or images. We
can change label text any time we want . If we want to underline the text
we can do that and also we can span text across multiple lines
Syntax
Simple syntax to create this widget −
x = Label ( master, option, ... )
50
The argument master represents the parent window and the argument Gui Programming in Python-II
option is the option used by label widget as a key-value pairs and they are
separated by comma.
Example 2:
importtkinter as tk
r = [Link]()
[Link](r,
text="Mumbai University",
fg = "red",
font = "Times").pack()
[Link](r,
text="python programming",
fg = "light green",
bg = "dark green",
font = "Helvetica 16 bold italic").pack()
[Link](r,
text="object oriented programming python",
fg = "blue",
bg = "yellow",
font = "Verdana 14 bold").pack()
[Link]()
51
Programming with Python– II Output:
Example:
importtkinter as tk
r = [Link]()
img1 = [Link](file="[Link]")
txt = "Hi, Student "
w = [Link](r, compound = [Link],
text=txt,
image=img1).pack(side="right")
[Link]()
Output:
d. check button,
The Checkbutton widget is used to display a number of options to a
user as toggle buttons. The user can then select one or more options
by clicking the button.
52
Syntax Gui Programming in Python-II
w = Checkbutton( master, option, ... )
Example
fromtkinter import *
r = Tk()
C1 = Checkbutton(r, text = "Python")
C2 = Checkbutton(r, text = "Java")
C3 = Checkbutton(r, text = "C++")
C4 = Checkbutton(r, text = "HTML")
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
Output:
e. entry
The Entry widget accepts single line text strings.
Syntax
e = Entry( master, option, ... )
Parameters
master − This represents the parent window.
options − These options can be used as key-value pairs separated by
commas.
53
Programming with Python– II
Option Description
Font The font used for the text.
Command A procedure to be called every time the user
changes the state of this check button.
Bg The normal background color displayed behind the
label and indicator.
Bd The size of the border around the indicator. Default
is 2 pixels.
exportselection By default, if you select text within an Entry
widget, it is automatically exported to the
clipboard. To avoid this exportation, use
exportselection=0.
Justify If the text contains multiple lines, this option
controls how the text is justified: CENTER, LEFT,
or RIGHT.
Example :
fromtkinter import *
t = Tk()
l1= Label(t, text="Enter Your Rollno")
[Link](side = LEFT)
e1 = Entry(t,bd=12)
[Link](side = RIGHT)
[Link]()
54
Output: Gui Programming in Python-II
f. list box
The listbox widget displays a list of items. The user can select the item
from the given list. ListBox can display different types of items. These
items must be of the same type of font and color. The user can select one
or more items from the given list according to the requirement.
Syntax
L=Listbox(master, option,…)
The argument master represents the parent window and the argument
option is the option used by Listbox widget as a key-value pairs and they
separated by comma.
Methods on listbox:
activate ( index ) Selects the line specifies by the index.
get ( first, last=None Returns a values containing the text of the lines
) with indices from first to last
curselection() Returns values containing the line numbers of the
selected element or elements, counting from zero.
delete ( first, Deletes the lines whose indices are in the range
last=None ) [first, last]
Example:
fromtkinter import *
t = Tk()
Lb1 = Listbox(t)
[Link](1, "Mumbai")
[Link](2, "Thane")
[Link](3, "Pune")
[Link](4, "Nashik")
[Link](5, "Nagpur")
[Link]()
[Link]()
55
Programming with Python– II Output
g. message
It is GUI element of tkinter. It is multiline and non-editable object. It
displays the static text. If length of message is large, it automatically
breaks the long text to multiple lines. It is similar to label widget. The only
difference is the message widget automatically wraps the text where the
label widget does not do automatically.
Syntax:
M=Message(master, option)
The argument master represents the parent window and the argument
option is the option used by message widget as a key-value pairs and they
separated by comma.
Example:
fromtkinter import *
t = Tk()
var1 = StringVar()
label1 = Message( t, textvariable=var1, relief=RAISED )
[Link]("It is GUI element of tkinter. It is multiline and non-editable
object.")
[Link]()
[Link]()
Output:
56
h. radio button Gui Programming in Python-II
The radio button is also known as option button. The option button allows
user to select values from the predefined set of values. Radio button
contains text as well as image. We can associate the function with the
option button when we select the option the function is called
automatically.
Example:
fromtkinter import *
t = Tk()
def function1():
selection = "selected your subject " + str([Link]())
[Link](text = selection)
var1 = IntVar()
R1 = Radiobutton(t, text="Python", variable=var1, value=1,
command=function1)
[Link]( anchor = W )
R2 = Radiobutton(t, text="Java", variable=var1, value=2,
command=function1)
[Link]( anchor = W )
R3 = Radiobutton(t, text="perl", variable=var1, value=3,
command=function1)
[Link]( anchor = W)
label = Label(root)
[Link]()
[Link]()
57
Programming with Python– II Output:
i. text
Text widget allows user to edit the multiline text. User can also format the
text the way user want to it display. User can change the color of the text,
foreground color as well as background color for the text and also user can
set the font of the text.
Syntax:
T= Text(master, option,…)
Method
Text object have following methods
Method Description
Get() This method returns a specific character of text.
Insert() This method inserts strings at the specified index
location.
See(index) This method returns true if the text located at the
index position is visible.
Index() Returns the absolute value of an index based on
the given index.
Example:
fromtkinter import *
t = Tk()
defonclick():
pass
text = Text(t)
[Link](INSERT, "Mumbai")
[Link](END, "University")
[Link]()
58
text.tag_add("123", "1.0", "1.4") Gui Programming in Python-II
text.tag_add("444", "1.8", "1.13")
text.tag_config("123", background="yellow", foreground="red")
text.tag_config("444", background="black", foreground="blue")
[Link]()
Output:
j. spin box
The spinbox contains the fixed number of values and it allows selecting
the value from the given values. It is a standard Tkinter Entry eidget.
Syntax:
s = Spinbox( master, option )
The argument master represents the parent window and the argument
option is the option used by message widget as a key-value pairs and they
separated by comma.
Option Description
from_ The minimum value.
Justify Default is LEFT
State One of NORMAL, DISABLED, or
"readonly".
To See from.
Validate Validation mode. Default is none
Width Widget width, in character units. Default is
20.
59
Programming with Python– II Example
fromtkinter import *
t = Tk()
s = Spinbox(t, from_=0, to=10)
[Link]()
[Link]()
Output
5.4 SUMMARY
Widget such as Button, Text, List, Radio button etc. call function
when user clicks on button and different widget.
60
UNIT-III
6
DATABASE & NETWORKING
CONNECTIVITY
Unit Structure
6.0 Objective
6.1 Introduction
6.2 Database connectivity in Python:
a. Installing mysql connector,
b. accessing connector module,
c. using connect,
d. cursor,
e. execute & close functions,
f. reading single & multiple results of query execution,
g. executing different types of statements,
h. executing transactions,
i. Understanding exceptions in database connectivity.
6.3 Network connectivity:
j. Socket module,
k. creating server-client programs,
l. sending email,
m. reading from URL
6.4 Summary
6.5 Reference for further reading
6.6 Unit End Exercises
6.0 OBJECTIVE
Understand Python and connector installation
61
Programming with Python– II
6.1 INTRODUCTION
Python supports various databases like MySQL, Oracle, Sybase, Postgre
SQL, etc. Python also supports Data Definition Language (DDL), Data
Manipulation Language (DML) and Data Query Statements. For database
programming, the Python DB API is a widely used module that provides a
database application programming interface.
Connector/Python Installation
Connector/Python runs on any platform where Python is installed. Python
comes preinstalled on most Unix and Unix-like systems, such as Linux,
macOS, and FreeBSD. On Microsoft Windows, a Python installer is
available at the Python Download website. If necessary, download and
install Python for Windows before attempting to install Connector/Python.
Connector/Python implements the MySQL client/server protocol two
ways:
• As pure Python; an implementation written in Python. Its
dependencies are the Python Standard Library and Python Protobuf>=
3.0.0.
• As a C Extension that interfaces with the MySQL C client library. This
implementation of the protocol is dependent on the client library, but
can use the library provided by MySQL Server packages (see MySQL
C API Implementations).
Obtaining Connector/Python
Packages are available at the Connector/Python download site. For some
packaging formats, there are different packages for different versions of
Python; choose the one appropriate for the version of Python installed on
your system.
• Windows MSI Installer (.msi file): To use the MSI Installer, launch it
and follow the prompts in the screens it presents to install
Connector/Python in the location of your choosing.
63
Programming with Python– II To include the C Extension (available as of Connector/Python 2.1.1),
use this command instead:
$> python [Link] install --with-mysql-capi="path_name"
The argument to --with-mysql-capi is the path to the installation directory
of MySQL Server.
To see all options and commands supported by [Link], use this
command:
$> python [Link] –help
c. using connect,
d. cursor, execute & close functions
To execute a SQL query in Python, you’ll need to use a cursor, which
abstracts away the access to database records. MySQL
Connector/Python provides you with the MySQLCursor class, which
instantiates objects that can execute MySQL queries in Python. An
instance of the MySQLCursor class is also called a cursor.
The first method, .execute(), works well when the number of records is
small and the records can be hard-coded. The second method,
.executemany(), is more popular and is better suited for real-world
scenarios.
Using .execute()
The first approach uses the same [Link]() method that you’ve been
using until now. You write the INSERT INTO query in a string and pass it
to [Link](). You can use this method to insert data into the movies
table.
Reading Records Using the SELECT Statement
To retrieve records, you need to send a SELECT query to [Link]().
Then you use [Link]() to extract the retrieved table in the form of a
list of rows or records.
Filtering Results Using the WHERE Clause
You can filter table records by specific criteria using the WHERE clause.
For example, to retrieve all movies with a box office collection greater
than $300 million, you could run the following query:
SELECT empno,ename
FROM emp
WHERE salary > 9000;
UPDATE Command
For updating records, MySQL uses the UPDATE statement
DELETE Command
Deleting records works very similarly to updating records. You use the
DELETE statement to remove selected records.
Example for connection:
[Link]
cnx = [Link](user='abc', password='123',
host='[Link]',
database='xyz')
[Link]()
Example for Connection using try
[Link]
[Link] import errorcode
65
Programming with Python– II try:
cnx1 = [Link](user='abc',
database='emp1')
[Link] as err1:
if [Link] == errorcode.ER_ACCESS_DENIED_ERROR:
print("wrong user name or password")
elif [Link] == errorcode.ER_BAD_DB_ERROR:
print("Database not found")
else:
print(err1)
else:
[Link]()
Create dictionary to hold connection information
dbConfig={
‘user’:<adminName>, #your Admin Nmae
‘password’:<adminpwd>,#admin password
‘host’:[Link],#local host ip address
}
For creating own database use following commands
GUID=”GuiDB”
Conn=[Link](**[Link])
[Link]()
try:
[Link](:CREATE DATABSE {} DEFAULT CHARACTER SET
‘utf8’”.
Format(GUIDB))
Except [Link] as err:
Print(“Failed to create database{}”.format(err))
[Link]()
In the above code we created the cursor object from connection object to
execute commands to MYSQL. A cursor is usually a place in a definite
row in a database table.
e. Reading single & multiple results of query execution, executing
different types of statements,executing transactions, Understanding
exceptions in database connectivity.
Retrieving record from table we used select command. where clause are
used with select command for matching particular condition.
66
Syntax: Database & Networking
Select Field No1, Field No 2, Connectivity
ENGINE=Innodb”)
INSERT Command:
Below code is use to insert record in Student Table
Table Info
Studentid
Student Name
Phy
Chem
BIO
Insert into tables values(value1,value2,….) query is used to insert new
record in table
Example
Import MySQLdb
db=[Link](“localhost”,”abc”,”123”,”database1”)
Cursor=[Link]()
Sql=”INSERT INTO STUDENT
(STUDENT_ID,STUDENT_NAME,PHY,CHEM,BIO)
Values(101,”xyz”,87,99,67)”
try:
[Link](sql)
[Link]()
[Link]()
UPDATE Command:
Update is used to update one or more records. We can use where with
UPDATE.
Syntax for UPDATE
UPDATE <table Name> Set <Field Name> where <Condition>
Import MySQLdb
db=[Link](“localhost”,”abc”,”123”,”database1”)
Cursor=[Link]()
Sql=”UPDATE STUDENT
Set Phy=67
Where Student_Id=101”
69
Programming with Python– II try:
[Link](sql)
[Link]()
except
[Link]()
[Link]()
Example for update all record in table
Update chemistry subject marks by 10% of each student
Import MySQLdb
db=[Link](“localhost”,”abc”,”123”,”database1”)
Cursor=[Link]()
Sql=”UPDATE STUDENT
Set chem=chem*.010”
try:
[Link](sql)
[Link]()
except
[Link]()
[Link]()
DELETE Command
DELETE command is use for delete record from table. To delete
particular record we used where with condition.
Syntax:
DELETE FROM <TABLE NAME>
Where Condition.
Example:
Import MySQLdb
db=[Link](“localhost”,”abc”,”123”,”database1”)
Cursor=[Link]()
Sql=”DELETE FROM STUDENT
Where Student_Id=101”
try:
[Link](sql)
[Link]()
except
70
[Link]() Database & Networking
[Link]() Connectivity
71
Programming with Python– II socket_type − This is either SOCK_STREAM or SOCK_DGRAM.
protocol − This is usually left out, defaulting to 0.
h. sending email,
When you send emails through Python, you should make sure that your
SMTP connection is encrypted, so that your message and login
credentials are not easily accessed by others. SSL (Secure Sockets
Layer) and TLS (Transport Layer Security) are two protocols that can be
used to encrypt an SMTP connection. It’s not necessary to use either of
these when using a local debugging server.
Using SMTP_SSL()
The code example below creates a secure connection with Gmail’s
SMTP server, using the SMTP_SSL() of smtplib to initiate a TLS-
encrypted connection. The default context of ssl validates the host name
and its certificates and optimizes the security of the connection.
importsmtplib, ssl
port = 465 # For SSL
password = input("Type your password and press enter: ")
# Create a secure SSL context
73
Programming with Python– II context = ssl.create_default_context()
withsmtplib.SMTP_SSL("[Link]", port, context=context) as
server:
[Link]("my@[Link]", password)
With Python you can also access and retrieve data from the internet
like XML, HTML, JSON, etc. You can also use Python to work with
this data directly. In this tutorial we are going to see how we can
retrieve data from the web. For example, here we used a guru99 video
URL, and we are going to access this video URL using Python as well
as print HTML file of this URL.
import urllib2
def main():
# open a connection to a URL using urllib2
webUrl = [Link]("[Link]
#get the result code and print it
print "result code: " + str([Link]())
# read the data from the URL and print it
data = [Link]()
print data
if __name__ == "__main__":
main()
6.4 SUMMARY
In this chapter we studied the use of database and Python.
Create table with constraints such as primary key, not null and foreign
key etc., and insert values in table.
74
6.5 REFERENCE FOR FURTHER READING Database & Networking
Connectivity
75