Unit 412
Unit 412
COURSE MATERIAL
For
Notes prepared by
P. Phani Prasad
Assistant Professor,
Department of CSE,
MVSREC
UNIT-IV
TOPICS COVERED
I. Exception Handling
1. Introduction to Errors & Exceptions
2. Brief about Built -in exceptions
3. Handling an exception using try, except blocks
4. Using multiple except blocks
5. Using except block without exception
6. else block
7. Finally block
8. Raising and instantiating an exception
9. Custom exceptions
II. File Handling
1. Introduction to files
2. Types of files
3. Modes of files
4. File operations
5. File positions
6. File paths
7. Renaming and deleting a file
III. GUI Programming
1. Introduction to GUI
2. Difference between terminal based applications and GUI applications
3. Creating a GUI window using Tkinter module
4. Tkinter widgets
a. Label
b. Entry
c. Button
d. Checkbutton
e. RadioButton
5. Tkinter geometry management
6. Event driven programming
7. Displaying notification dialog boxes
8. Example programs
a. Creating a Login application
b. Building a registration form
b. Logical error: An error that occurs due to producing a wrong result for the given
problem.
For example, producing division results if the given problem is to compute addition
operation.
Logical errors come during the execution of the program. They occur because of
misunderstanding of the given problem by users.
c. Runtime error: An error that occurs when python fails to execute an instruction and
causes abnormal termination of the program.
What is an Exception?
An exception is a runtime error that interrupts and deviates the normal flow of the program
execution and leads to abnormal termination of program.
➔ When an exception occurs at a line,python fails to take a necessary action on that line.
This causes the program to terminate abruptly without executing further error free lines.
➔ To stop the program from abnormal termination, an exception must be handled by
suspecting it.
➔ Python provides many built-in exception handling classes based on the nature of
exception.
➔ For example, the below line throws ZeroDivisionError when trying to divide a number
with zero.
●
●
Few of the built-in exceptions are described below.
Syntax
try:
#statements
#error statement-1
#error statement-2
…
#error statement-N
except Exception1 as errorVariable-1:
#statements to handle error statement-1
except Exception2 as errorVariable-2:
#statements to handle error statement-2
….
except ExceptionN as errorVariable-N:
#statements to handle error statement-N
Example :
The below program handles 3 exceptions:ValueError, ZeroDivisionError, IndexError
Example:
The below program handles 3 exceptions:ValueError, ZeroDivisionError, IndexError using
BaseException
Output-1
Output-2
Output-3
Output-4
Example: The below program raises 3 types of errors but except block prints common error
message to all types of errors
Output -1 Output -2
6. else block
● “else” is a special block which executes only when all the statements in the try block are
executed without raising any exception.
● “else” block ensures that the try block is executed successfully and it is exception free.
● “else” block is an optional block which should be written immediately after the except
block.
● “else” block will be skipped from the execution if atleast one exception is raised in the try
block.
● Syntax:
try:
#statements
except :
#statements
else:
#statements
● Example:
Output -1 Output -2
7. “finally” block
● “Finally” block is a special block that executes irrespective of error occurs in the
program.
● That means , this block will execute if error occurs in the program and if errors do not
occur in the program.
● The main purpose of this block is to perform clean up activity. That means releasing of
resources utilized by the program such as closing the opened file, disconnecting database
connections, disconnecting network communication etc.
● If any error occurs in the program, the resources used by the program will run
continuously until the program abruptly terminates and that is of no use.
● So the “finally” block completes this clean up activity before terminating the program.
● “finally” executes in three cases:
○ If no error occurs,try and finally executes
○ If errors occurs and handled, except block and finally block executes
○ If error occurs , but not handled, finally the block executes and the program
terminates abruptly.
● Syntax
Output
Output
Output
9. Custom exceptions
● The process of creating our own exceptions is known as custom exceptions or user
defined exceptions.
● Python supports many built-in exceptions, but these exceptions may not be reasonable to
use in real time applications that involve more human interactions.
● For example, assume you went to an ATM to withdraw money from account-X. If
account-X has Rs.500 amount as balance but withdrawing Rs.1000 then the system
should display a reasonable message “Insufficient balance in account” but not IndexError
or ValueError or something else.
● So to create such kind of user defined error messages we use custom exceptions.
Output -1
Output-2
3. Modes of files
Mode of a file specifies the type of operation on the file such as file opened for writing or
reading etc.
Python supports twelve modes of files. Six modes are for text files and six modes are for
binary files which are described below.
1 “w” Text file opened in write mode. Creates a new file if file not
found
3 “a” Text file opened in append mode. Creates a new file if file
not found
4 “w+” Text file opened in both write/read mode. Creates a new file
if file not found
7 “wb” Binary file opened in write mode. Creates a new file if file
not found
9 “ab” Binary file opened in append mode. Creates a new file if file
not found
“Append” mode preserves the previous data and also adds new data to the end of
the text/binary file.
Both modes will create a new file if the file is not found.
4. File operations
In python, a file is used to perform following operations:
a. Creating a new file
b. Writing data to the file
c. Reading the data from an existing file
d. Appending the data to the file
e. Closing the file
Creating a new file: We can create a new file at a specified location in the hard
disk drive. Python has built-in function “open()” to create a new file.
To create a new file, file mode should be either “write” mode or “append” mode.
Syntax to create a new file:
fileVariable=open(filename,filemode)
Example to create a new file:
file=open(“demo.txt”,”w”)
We can create a new file using the “with” keyword. Below is the syntax.
with open(filename,filemode) as fileVariable:
#file related statements
Example:
with open(“demo.txt”,w”) as file:
print(“file created”)
Note: Files created using “with” keyword will be closed automatically without calling
close() function. If “with” is not used then the file should be opened and closed explicitly by
calling close() function.
Writing data to the file: After creating a new file, we can write data to the file using the
built-in functions write() and writelines().
write() function writes a string of data to file whereas writelines() function writes list of strings to
the file.
Syntax:
with open(filename,filemode) as fileVariable:
#fileVariable.write(stringdata)
# fileVariable.writeline(listdata)
Example-1:
with open(“demo.txt”,w”) as file:
print(“file created”)
data=”hello world”
file.write(data)
Example-2:
demo.txt
Example-1
Output-1
Example-2
Output-2
Example-3
Output-3
Example-4
Output-4
demo.txt (before
append)
Example
Output
demo.txt (after
append)
Note: if file is opened using “with” keyword, we no need to call close() as file will be closed
automatically.
Example:
file=open(“demo.txt”,”r”)
print(“file opened”)
file.close()
print(“file closed”)
5. File attributes
In python a file is an object that has built-in methods and attributes.
File attributes specify the file information such as file name, file mode, file size, file closed or
not etc.
Below are a few frequently used file attributes.
6. File positions
When a file containing some data is opened, a file cursor is internally maintained by the file
object. File cursor is used to indicate the current position of the file when data is written or read.
we can perform a few below special operations on file. We can
→ fetch the current position of the file
→ set the position of a file
The below example returns the current position of file after reading 10 characters from
file and reading total data from the file.
Output
Example program:
Output
7. File paths
After creating a file using the open() function, we can access the path of the file.
Path of the file can be of two types:
i) Absolute path: the complete path of the file from the root directory to the file location.
ii) Relative path: it is a portion of the absolute path of the file which is not complete. It
specifies the path from the parent directory to the file.
As a user we can decide from which parent directory, the file path should be fetched.
File objects don’t have built-in methods to get the path of the file.
To change the name of a file, we need to import the “os” module and call abspath() function and
relapth() function to fetch absolute path and relative path respectively.
Syntax:
import os
with open(filename,filemode) a fileVariable:
os.apth.abspath(filename)
ps.relpath(filename,pathtoExclude)
Example:
Below example prints both absolute path and relative path of the file “demo.txt”
Output
Output
Example Programs
1. Program to copy the contents from one file to another file
Solution:
2. Program to copy data from one file to another file and inserts line numbers in the
copied file
Solution:
1. Introduction to GUI
● What is GUI? Graphical User Interface (GUI) is one of the most usable user interfaces
for interacting with the python application in any operating system like windows, linux,
macos etc.
● Using GUI, users interact with applications through clickable graphical components like
buttons, menus, checkbox, radiobutton, entry fields, dropdown lists etc.
● It provides a user-friendly interface that users feel comfortable to interact with programs.
● All inputs and outputs to the application happens through gui windows.
2. Difference between terminal based applications and GUI applications
User interacts with the application User interacts with the application using
in the form plain text graphical components like clickable
buttons,icons,images etc.
Low memory usage and less High memory usage and high flexible user
flexible user interface interface
Program Output
4. Tkinter widgets
Python allows many built-in graphical components called Widgets to be inserted inside
Tkinter main window and allows configuring them. Few of them are described below.
a. Label
It is a tkinter gui widget to display static text on the tkinter window.
Label is not an interactive component, it is just used to guide the user to
interact with the application.
Syntax
variable=Label(text=”Text to display”,[configuration
parameters])
Example
l1=Label(text=”Enter name:”)
b. Entry
It is a tkinter gui widget that allows you to enter a single-line input text.
The text entered by default will be stored as a String. Later it should be
type casted to required type explicitly.
Syntax:
variable=Entry(width=value,textvariable=variableName,[confi
guration parameters])
Example-1
e1=Entry(width=10,textvariable=v1)
#This statement creates an Entry component of width 10pixels. Input will
be stored in the v1 variable.
Example-2
e1=Entry(width=10,textvariable=v1,show=’*’)
#This statement creates an Entry component of width 10pixels. Input will
be stored in the v1 variable and entered data will be masked with “*”.
Used to enter passwords.
Structure :
c. Button
It is a tkinter gui widget that represents a clickable item in the application.
Button requires actions to be invoked upon click. So it takes a special
parameter “command” to map the clicks to the corresponding action to
invoke.
Syntax:
variable = Button(text=”Text to display”,
command=functionName,[configuration parameters])
Example:
b1=Button(text=”click me”)
Structure:
d. Checkbutton
A checkbox is a widget that allows you to check and uncheck.
A checkbox can hold a value and invoke a callback when it’s checked or
unchecked.
Typically, we use a checkbox when we want to collect data from multiple
selections.
We need to import the “ttk” sub-module from tkinter to use Checkbutton.
Syntax:
variable=Checkbox(text=”text to display”,
variable=variableName)
text → specifies the text to display on screen
tariable → stores two possible values in the given variable. When the
checkbox is selected the value assigned will be 1,if it is not selected then
value will be 0.
Example to create 3 checkboxes to check languages known:
cb1=Checkbox(text=’C’,variable=v1)
cb2=Checkbox(text=’python’,variable=v2)
cb3=Checkbox(text=’java’,variable=v3)
Structure:
e. Radiobutton
It is a gui widget that allows you to select only one option from the given
multiple choices.
All radio buttons must be grouped with a common variable such that it
stores only one value which is selected.
Syntax
rb1=Radiobutton(text=”text to display”,
variable=variableName,value=numericvalue)
Example
rb1=Radiobutton(text='Male',variable=v5,value=1)
rb2=Radiobutton(text='Female',variable=v5,value=2)
Observe that two radio buttons rb1,rb2 has same variable name v5 which
is grouped together. If rb1 selected, v5 value is 1 else v5 value is 2
Structure:
f. Combobox
It is a gui widget that allows you to generate a drop down list of items.
User has to select one item from the list of items.
We need to import the “ttk” sub-module from tkinter to use Combobox.
Syntax:
cbb=ttk.Combobox(textvariable=variable)
cbb['values']=(tuple of items)
cbb['state']='readonly'
Note:
cbb[‘values’] → used to set the items to be displayed for combobox
cbb[‘read-only’] → set the combobox items to be immutable.
Example:
cbb=ttk.Combobox(textvariable=v4)
cbb['values']=('CSE','ECE','EEE','IT','CIVIL','MECH')
cbb['state']='readonly'
Structure :
Output
● To cover all of these scenarios, you can use various functions from the
"tkinter.messagebox" module:
○ showinfo() – notify that an operation completed successfully.
○ showerror() – notify that an operation hasn’t completed due to an
error.
○ showwarrning() – notify that an operation completed but
something didn’t behave as expected.
Syntax:
All of these functions accept two arguments:
showinfo(title,message)
showerror(title,message)
showwarning(title,message)
Example:
def compute():
messagebox.showinfo(“Notify”,”button
clicked”)
btn=Button(text=”click me”)
btn.bind(‘<Enter>’,compute)
Program:
Below program creates a gui window with a label, entry and button. An alert notification will be
displayed when the button is clicked.
Output -1
Output -2
Output -3
9. Example programs
a. Create a GUI to perform addition of two numbers
Program:
Output
Output -1
Output -2
Program:
v1=StringVar()
v2=StringVar()
v3=StringVar()
v4=StringVar()
v5=IntVar()
v6=IntVar();v7=IntVar();v8=IntVar()
def clear():
v1.set("")
v2.set("")
v3.set("")
v4.set("")
v5.set(0)
v6.set(0)
v7.set(0)
v8.set(0)
def save():
a=v6.get();b=v7.get();c=v8.get();d=v5.get()
cbdata="";rbdata=0
if d==1:
rbdata='Male'
else:
rbdata='Female'
if a==0 and b==0 and c==0:
cbdata="None"
elif a==1 and b==1 and c==1:
cbdata="C,Python,Java"
elif a==0 and b==0 and c!=0:
cbdata="Java"
elif a==0 and b!=0 and c==0:
cbdata="Python"
elif a!=0 and b==0 and c==0:
cbdata="C"
elif a!=0 and b!=0 and c==0:
cbdata="C,Python"
elif a!=0 and b==0 and c!=0:
cbdata="C,Java"
elif a==0 and b!=0 and c!=0:
cbdata="Python,Java"
with open('save.txt','w') as f:
f.write("Student Details are:\n==========\n")
f.write("Name="+v1.get())
f.write("\nRoll number="+v2.get())
f.write("\nBranch="+v4.get())
f.write("\nGender="+rbdata)
f.write("\nEmail="+v3.get())
f.write("\nLanguages Known="+cbdata)
messagebox.showinfo("Message","Student details saved
successfully...!")
l1=Label(text='Enter student name:')
l2=Label(text='Enter Roll number:')
l3=Label(text='Select branch:')
l4=Label(text='Select Gender:')
l5=Label(text='Enter Email:')
l6=Label(text='Prog. languages Known:')
l7=Label(text='Enter Address:')
e1=Entry(width=20,textvariable=v1)
e2=Entry(width=20,textvariable=v2)
e3=Entry(width=20,textvariable=v3)
e4=Text(width=20,height=3)
rb1=Radiobutton(text='Male',variable=v5,value=1)
rb2=Radiobutton(text='Female',variable=v5,value=2)
cb1=Checkbutton(text='C',variable=v6)
cb2=Checkbutton(text='Python',variable=v7)
cb3=Checkbutton(text='Java',variable=v8)
cbb=ttk.Combobox(textvariable=v4)
cbb['values']=('CSE','ECE','EEE','IT','CIVIL','MECH')
cbb['state']='readonly'
b1=Button(text='Save',command=save)
b2=Button(text='Clear',command=clear)
b3=Button(text='Quit',command=tk.destroy)
l1.grid(row=3,column=5)
e1.grid(row=3,column=7)
l2.grid(row=5,column=5)
e2.grid(row=5,column=7)
l3.grid(row=7,column=5)
cbb.grid(row=7,column=7)
l4.grid(row=9,column=5)
rb1.grid(row=9,column=7)
rb2.grid(row=9,column=10)
l5.grid(row=11,column=5)
e3.grid(row=11,column=7)
l6.grid(row=13,column=5)
cb1.grid(row=13,column=7)
cb2.grid(row=13,column=9)
cb3.grid(row=13,column=11)
l7.grid(row=15,column=5)
e4.grid(row=15,column=7)
b1.grid(row=17,column=5)
b2.grid(row=17,column=8)
b3.grid(row=17,column=11)
tk.mainloop()
Output
saved file