0% found this document useful (0 votes)
24 views89 pages

Unit V

The document provides an overview of file operations, error handling, and simple graphics in Python programming. It covers file types, modes for opening files, reading and writing methods, and exception handling techniques, including user-defined exceptions. Additionally, it introduces basic graphics using the turtle library.

Uploaded by

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

Unit V

The document provides an overview of file operations, error handling, and simple graphics in Python programming. It covers file types, modes for opening files, reading and writing methods, and exception handling techniques, including user-defined exceptions. Additionally, it introduces basic graphics using the turtle library.

Uploaded by

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

JCS2201-PYTHON PROGRAMMING

S.Gayathri
Assistant Professor
Department of Computer science and Engineering
Jerusalem College of Engineering
UNIT V FILES EXCEPTIONS AND GUI
,

Files: Basic file operations and access methods . Errors and Exceptions:
Syntax Errors, Exception types ,Handling Exceptions, Raising Exceptions,
Simple graphics: simple 2D drawing shapes and coloring. GUI using
Tkinter.
FILES:
• A file can be defined as a location for storing related data.
• A file holds a specific name for itself.
• A file can be a sequence of bits, bytes, lines or records depending on
the application used to create it.
Example:
sample.py, student.txt
Here sample, student are the file names with file extensions
Types of files:
Text files:
• A text file is a file containing characters structured as individual lines
of text.
• In addition to printable characters, text files also contain the non
printing new line character \n to denote the end of each text line
Binary files:
• Binary files can contain various types of data, such as numerical
values. These are not structured as lines of text.
• Such files can only be read and written via a computer program
Different Modes to Open a File in Python
FILE OPERATIONS:
1.Opening a file
2.Reading from a file
3.Writing to a file
4.Appending a file
5.Closing a file
Opening a file
➢All files must be opened first before they can be used.
➢In python, when a file is opened, a file object is created that provides
methods for accessing the file.
➢ In python there is a built in function open() to open a file.
Syntax:
file_object=open(filename,accessmode)

• where file_object is used as a handle to the file


• file_name- string type value containing the name of the file
• access_mode-specifies the mode in which we want to open the file
Example for opening a file
fp1=open("sample.txt","w")
print(fp1)
fp=open("sample.txt","r")
print(fp)
Output:
<_io.TextIOWrapper name='sample.txt' mode='w' encoding='cp1252'>
<_io.TextIOWrapper name='sample.txt' mode='r'encoding='cp1252'>
Example for opening a file when the file does not exists
fp1=open("sample1.txt","r")
print(fp1)
Output:
fp1=open("sample1.txt","r")
FileNotFoundError: [Errno 2] No such file or directory: 'sample1.txt'
PYTHON FILE OPENING MODES:
File object attributes:
• Once a file is opened and a file object is created, various pieces of
information about the file can be gathered by using some predefined
attributes.
• four types of attributes as shown below:
File object attributes
fp=ope("sample.txt","r")
print("Name of the file",fp.name)
print("closed or not",fp.closed) Output:
Name of the file sample.txt
print("opening mode",fp.mode) closed or not False
print("File object",fp) opening mode r
File object <_io.TextIOWrapper name='sample.txt'
fp.close() mode='r' encoding='cp1252’>
print("Name of the file",fp.name)
Name of the file sample.txt
print("closed or not",fp.closed) closed or not True
print("opening mode",fp.mode) opening mode r
File object <_io.TextIOWrapper name='sample.txt'
print("File object",fp) mode='r' encoding='cp1252'>
Reading from a file
• In order to read from a file, the file must be opened in r mode. A file can be read in four
different ways:
➢read(size)
➢ readline()
➢ readlines()
➢ loop
read() method:
The read() enables reading the contents of an opened file.
Syntax:
fileobject.read()
fileobject.read(size)
• where size argument is optional. When the size is not specified, the entire file is read.
When the size is specified, the size number of characters is read. When an empty file is
read, no error is thrown but an empty string is returned.
readline() method:
• This method is used for reading a file line by line. This method reads a file till the
new line character including the newline character.
Syntax:
fileobject.readline()
fileobject.readline(size)
• where size is optional. When size is specified the size number of characters are
read,otherwise it is similar to read()
readlines() method:
• The readlines() method returns a list of lines of the entire file.
Syntax:
• fileobject.readlines()
• fileobject.readlines(size)
When size is not specified, the entire file is read and each line is added as an
element in a list.
Using loop:
A file can be read line by line using for loop
Syntax:
for line in <filevariablename>:
statements for file operations
Example for reading a file using various methods:
• Let sample1.txt be the file
Reading a file using read() method
fp=open("sample1.txt","r")
print("Read a file using read()")
print(fp.read())
fp.close()
Output:
Read a file using read()
This is line1 in file reading operation
This is line2
This is line3
This is line4
Reading a file using read(size) method
fp=open("sample1.txt","r")
print("Read a file using read(size)")
print(fp.read(10))
fp.close()
Output:
Read a file using read(size)
This is li
Reading a file using readline() method
fp=open("sample1.txt","r")
print("Read a file using readline()")
print(fp.readline())
fp.close()
Output:
Read a file using readline()
This is line1 in file reading operation
Reading a file using readlines()methods
fp=open("sample1.txt","r")
print("Read a file using readlines()")
print(fp.readlines())
fp.close()
Output:
Read a file using readlines()
['This is line1 in file reading operation\n', 'This is line2\n', 'This is
line3\n', 'This isline4']
Reading a file using loop
fp=open("sample1.txt","r")
for line in fp:
print("The contents of the file are")
print(line)
fp.close()
Output:
The contents of the file are
This is line1 in file reading operation
The contents of the file are
This is line2
The contents of the file are
This is line3
The contents of the file are
This is line4
Writing to a file
• In order to write into a file, the file has to be opened in “w” mode or
“a” mode or any other writing mode. The “w‟ mode overwrites the
file if the file already exists. If the file does not exist, a new file is
opened for writing.
Syntax:
fileobject=open(“filename”,”w”)
The write operation can be done using the following ways:
➢write()
➢writelines()
write() method:
• The write method puts data into the file.
• The write() method writes any string to an open file.
• The write() method does not add a newline character ('\n') to the end
of the string
Syntax:
fileobject.write(string)
Where string is the content that is written to the file
writelines()
• The writelines method puts multiple data into the file. The
writelines() method writes any string to an open file.
Syntax :
fileobject.writelines(string)
Example
Writing to a file when the file already exists
fp=open("sampletest.txt","w")
fp.write("This content is written to the file")
fp.close()
Output:
• Before write operation
After write operation
Example:
Writing to a file using write()
fp=open("samp.txt","w")
fp.write("This content is written to the file using write()")
fp.close()
Example:
Writing to a file using writelines()
fp=open("samp1.txt","w")
fp.writelines("This content is written to the file using writelines()\nThis
is line2")
fp.close()
Closing a file:
• When the operations that are to be performed on an opened file are
finished, the file has to be closed in order to release the resources.
Proper closing of file frees up the resources held with the file. The
closing of file is done with the built-in function close()
Syntax:
fileobject.close()
Example:

Closing a file
fp=open("new.txt","r")
print(fp.read())
fp.close()
Output:
This file is closed
Closing a file using with:
A file can also closed using with the statement as follows:
Syntax:
with open(“filename”,accessmode) as fileobject:statements for file
operations
Example:
with open("new.txt","r") as fp:print(fp.read())
fp.close()
Output:
This file is closed
ERRORS AND EXCEPTIONS
There are two kinds of errors:
syntax errors and exceptions.
Syntax Errors
• Syntax errors, also known as parsing errors.
• Syntax error is an error in the syntax of a sequence of characters or
tokens that is intended to be written in python. For compiled
languages, syntax errors are detected at compile-time. A program will
not compile until all syntax errors are corrected.
• For interpreted languages, however, a syntax error may be detected
during program execution, and an interpreter's error messages might
not differentiate syntax errors from errors of other kinds.
Exceptions
• Even if a statement or expression is syntactically correct, it may cause
an error when an attempt is made to execute it. Errors detected
during execution are called exceptions.
• You will soon learn how to handle them in Python programs. Most
exceptions are not handled by programs, however, result in error
messages as shown here:
>>> 55+(5/0)
Traceback (most recent call last):
File "<pyshell#12>", line 1, in
<module> 55+(5/0)
Zero DivisionError: integer division or modulo by zero

>>> 5+ repeat*2
Traceback (most recent call last):
File "<pyshell#13>", line 1, in
<module> 5+ repeat*2
NameError: name 'repeat' is not defined

>>> '5'+5
Traceback (most recent call last):
File "<pyshell#14>", line 1, in
<module> '5’+5
TypeError: cannot concatenate 'str' and 'int' objects
Exception Handling Clauses
HANDLING EXCEPTIONS
• Python provides two very important features to handle any
unexpected error in your
Python programs and to add debugging capabilities in them.
Exception Handling:
• An exception is an event, which occurs during the execution of a
program that disrupts the normal flow of the program's instructions.
• In general, when a Python script encounters a situation that it cannot
cope with, it raises an exception.
• When a Python script raises an exception, it must either handle the
exception immediately otherwise it terminates and quits.
• If you have some suspicious code that may raise an exception, you
can defend your program by placing the suspicious code in a try: block.
After the try: block, include an except: statement, followed by a block
of code which handles the problem.
Python Exception clause
Try Except Finally clause
• The try block lets you test a block of code for errors.
• The except block lets you handle the error.
• The finally block lets you execute code, regardless of the result of the
try- and except blocks.
Example
The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")
Output:
exception occurred
Example
This statement will raise an error, because x is not defined:
print(x)
Output:
Traceback (most recent call last):
File "demo_try_except_error.py", line 3, in <module>
print(x)
NameError: name 'x' is not define
Many Exceptions
• You can define as many exception blocks as you want, e.g. if you want to
execute a special block of code for a special kind of error:
Example
• Print one message if the try block raises a NameError and another for other
errors:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Output:
Variable x is not defined
Else
You can use the else keyword to define a block of code to be executed if no
errors were raised:
Example
In this example, the try block does not generate any error:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Output:
Hello
Nothing went wrong
Finally
The finally block, if specified, will be executed regardless if the try block
raises an error or not.
Example
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Output:
Something went wrong
The 'try except' is finished
Raise an exception
As a Python developer you can choose to throw an exception if a
condition occurs.To throw (or raise) an exception, use the raise
keyword.
Example:
Raise an error and stop the program if x is lower than 0:
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
Output:
Traceback (most recent call last):
File "demo_ref_keyword_raise.py", line 4, in <module>
raise Exception("Sorry, no numbers below zero")
Exception: Sorry, no numbers below zero
You can define what kind of error to raise, and the text to print to the
user.
Example
Raise a TypeError if x is not an integer:
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
Output:
Traceback (most recent call last):
File "demo_ref_keyword_raise2.py", line 4, in <module>
raise TypeError("Only integers are allowed")
TypeError: Only integers are allowed
User defined Exception:
• Python has many built-in exceptions.
• However, sometimes you may need to create custom exceptions that
serves your purpose.
• In Python, users can define such exceptions by creating a new class.
This exception class has to be derived, either directly or indirectly, from
Exception class. Most of the built-in exceptions are also derived form
this class
>>> class CustomError(Exception):
... pass
...
>>> raise CustomError
Traceback (most recent call last):
...__main__.CustomError
>>> raise CustomError("An error occurred")
Traceback (most recent call last):
...
__main__.CustomError: An error occurred

• Here, we have created a user-defined exception called CustomError which


is derived from the Exception class. This new exception can be raised, like
other exceptions, using the raise statement with an optional error
message.
Example: User-Defined Exception in Python
• This program will ask the user to enter a number until they guess a stored
number correctly.
• hint is provided whether their guess is greater than or less than the stored
number.

# define Python user-defined exceptions


class Error(Exception):
"""Base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass
class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass
# our main program
# user guesses a number until he/she gets it right
# you need to guess this number
number = 10
while True:
try:
i_num = int(input("Enter a number: "))
if i_num < number:
raise ValueTooSmallError
elif i_num > number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")
except ValueTooLargeError:
print("This value is too large, try again!")
print("Congratulations! You guessed it correctly.")

OUTPUT
Enter a number: 12
This value is too large, try again!
Enter a number: 0
This value is too small, try again
Enter a number: 10
Congratulations! You guessed it correctly.
Simple Graphics
• turtle is a Python library to draw graphics.
• After we import turtle we can give commands likeforward, backward, right,
left etc.
Simple Turtle Commands
➢ forward(10) → It moves the turtle (arrow) forward by 10 pixels.
➢ backward(5) → It moves the turtle (arrow) backward by 5 pixels
➢ right(35) → It moves the turtle (arrow) clockwise by an angle of 35
degrees.
➢ left(55) → It moves the turtle (arrow) counter-clockwise by an angle of 55
degrees
➢ goto(x,y) → It moves the turtle (arrow) to the position x, y
➢ dot() → It creates a dot in the current position.
➢ shape(‘circle’) → It draws a circle shape.
Examples
Draw a Star
appropriate steps is to move the cursor forward and then turn right

import turtle
star = turtle.Turtle()
for i in range(100):
star.forward(100)
star.right(144)
turtle.done()
Output:
Multiple Squares
multiple squares all starting from a common point.
forward, backward to draw line and left ,right for direction turn 90 degrees.
Example
import turtle
mult_square=turtle.Turtle()
def Multiple_Squares(length, colour):
mult_square.pencolor(colour)
mult_square.pensize(2)
mult_square.forward(length)
mult_square.right(90)
mult_square.forward(length)
mult_square.right(90)
mult_square.forward(length)
mult_square.right(90)
mult_square.forward(length)
mult_square.right(90)
mult_square.setheading(360)
for i in range(60,120,15):
Multiple_Squares(i,'blue')
turtle.done
Output:
2D-GRAPHICS-COLORS-SHAPES

• turtle is an inbuilt module in python. It provides drawing using a


screen (cardboard) and turtle (pen).
• To draw on the screen, we need to move the turtle. To move turtle,
there are some functions i.e forward(), backward().
• To fill the colors in the shapes drawn by turtle. Three functions are
available
• fillcolor(): This helps to choose the color for filling the shape. It takes
the input parameter as the color name or hex value of the color and
fills the upcoming closed geographical objects with the chosen color.
• Color names are basic color names i.e. red, blue, green, orange.
• The hex value of color is a string(starting with ‘#’) of hexadecimal
numbers i.e. #RRGGBB. R, G, and B are the hexadecimal numbers (0,
1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F).
• begin_fill(): This function tells turtle that all upcoming closed
graphical objects needed to be filled by the chosen color.
• end_fill(): this function tells turtle to stop the filling upcoming closed
graphical objects.
import turtle
# creating turtle pen
t = turtle.Turtle()
# taking input for the side of the square
s = int(input("Enter the length of the side of the square: "))
# taking the input for the color
col = input("Enter the color name or hex value of color(# RRGGBB): ")
# set the fillcolor
t.fillcolor(col)
# start the filling color
t.begin_fill()
# drawing the square of side s
for _ in range(4):
t.forward(s)
t.right(90)
# ending the filling of the color
t.end_fill()
Output:
Enter the length of the side of the square: 90
Enter the color name or hex value of color(# RRGGBB): green
Output:
• Enter the length of the side of the square: 90
• Enter the color name or hex value of color(# RRGGBB): #F10000
# draw color filled triangle in turtle
import turtle
# creating turtle pen
t = turtle.Turtle()
# taking input for the side of the triangle
s = int(input("Enter the length of the side of the triangle: "))
# taking the input for the color
col = input("Enter the color name or hex value of color(#RRGGBB): ")
# set the fillcolor
t.fillcolor(col)
# start the filling color
t.begin_fill()
# drawing the triangle of side s
for _ in range(3):
t.forward(s)
t.right(-120)
# ending the filling of the color
t.end_fill()
Output:
Enter the length of the side of the triangle: 100
Enter the color name or hex value of color(#RRGGBB): blue
TKinter
Tkinter
Tkinter is Python’s standard GUI (Graphical User Interface) package.
tkinter provides variety of common GUI elements which we can use to
build interface – such as buttons, menus and various kind of entry
fields and display areas.
Widgets
Widget is an element of Graphical User Interface (GUI) that
displays/illustrates information or gives a way for the user to interact
with the OS. In Tkinter , Widgets are objects ; instances of classes that
represent buttons, frames, and so on.
To create Tkinter app in Python:
1. In Python 2.x, import Tkinter while in Python 3.x, import tkinter
2. Create a main window (container) for all GUI elements.
3. Add widgets to the main window like buttons, labels, check button,
etc.
4. Apply event triggers to the widgets to define how they respond to
user interactions
Here are some of the widgets available:
To create a main window Tk():
Tk (screenname=None, baseName=None, className= ‘Tk’, useTk=1)
- To change window name change className
• mainloop() is an infinite loop used to run the application, wait for an
event to occur and process the event as long as the window is not
closed
Creating GUI using tkinter:
Example:
import tkinter
tp=tkinter.Tk()
tp.mainloop()
Tkinter Widgets:
1. Label
Syntax:
W=Label (master, option=value)
master is the parameter to represent parent window
Example:
import tkinter as tk
m=tk.Tk()
label =
tk.Label(m,text="Hello,Tkinter",fg="white",bg="black",width=10,height=1)
label.pack()
m.mainloop()
2.Button:
widgets used to display clickable buttons.
Syntax:
Button (master, option = value)
Parameters:
• master: This argument is used to represent or declare the root or
parent window.
• option: There are different values for options in the button widgets
such as activebackground color, activeforeground color, bg, font,
image, width, height, command, etc
Example:
import tkinter as tk
m=tk.Tk()
b1 = tk. Button(m, text="Click me!", width=25,height=5, bg="blue",
fg="yellow")
b1.pack()
m.mainloop()
3. Input With Entry Widgets:
• Displays text box where user can type texts.
Example:
import tkinter as tk
m=tk.Tk()
label = tk.Label(m, text="Name")
entry=tk.Entry()
label.pack()
entry.pack()
m.mainloop()
4.Check button:
• used to store or record status like on or off, true or false, etc., which
means these are like buttons but used when the user wants to choose
between two different values or status. In this, the user can select
more than one checkbox. Let us see an
• example of how this button works. Options can be like the title for
giving the title to the widget, activebackground, and
• activeforeground for setting back and foreground color, bg for setting
up the background color, command, font, image, etc.
• Syntax:
• w=CheckButton (master, option=value)
Example:
from tkinter import *
root = Tk()
v1 = IntVar()
Checkbutton(root, text='Python',width =25, variable=v1).grid(row=0,
sticky=S)
v2 = IntVar()
Checkbutton(root, text='Unix',width =25, variable=v2).grid(row=1, sticky=S)
v3 = IntVar()
Checkbutton(root, text='Perl',width =25, variable=v3).grid(row=2, sticky=S)
mainloop()
5.Radio Button:
• similar to the checkbutton, but this widget is used when the user is
given many different options but is asked to select only one among
the options. The radiobutton widget must be associated with the
same
• variable, and each symbolizes a single value.
Syntax:
RadioButton (master, option = values)
Options are the same as for check buttons.
Example:
from tkinter import *
root = Tk()
v = IntVar()
Radiobutton(root, text='male',width =25, variable=v,
value=1).pack(anchor=W)
Radiobutton(root, text='female',width =25, variable=v,
value=2).pack(anchor=W)
Radiobutton(root, text='others',width =25, variable=v,
value=3).pack(anchor=W)
mainloop()
6. MenuButton
• Associated with a menu widget and displays the selected option
when user clicks on it. MenuButton is part of a dropdown menu that
is always present on the window.
Syntax:
MenuButton (master, option = value)
Example:
from tkinter import *
root = Tk()
root.geometry("300x350")
menubutton = Menubutton(root, text = "File", width = 35)
menubutton.grid()
menubutton.menu = Menu(menubutton)
menubutton["menu"]=menubutton.menu
menubutton.menu.add_checkbutton(label = "New file", variable=IntVar())
menubutton.menu.add_checkbutton(label = "Save", variable = IntVar())
menubutton.menu.add_checkbutton(label = "Save as",variable = IntVar())
menubutton.pack()
root.mainloop()
7. Frame: is a rectangular region on the screen to implement complex widgets and
to organize a group of widgets.
Syntax:
w= Frame( master, options)
import tkinter as tk
m=tk.Tk()
frme1 = tk.Frame()
lbl1=tk.Label(frme1, text="I’m in Frame A")
lbl1.pack()
frme2= tk.Frame()
lbl2=tk.Label(frme2, text="I’m in Frame B")
lbl2.pack()
frme2.pack()
frme1.pack()
m.mainloop()
Create a simple registration form using Tkinter
Example:
import tkinter as tk
from tkinter import messagebox
def submit_form():
username = entry_username.get()
password = entry_password.get()
# You can add further validation or processing here
messagebox.showinfo("Registration Successful", f"Welcome,
{username}!")
# Create the main window
root = tk.Tk()
root.title("Registration Form")
# Create and place widgets
label_username = tk.Label(root, text="Username:")
label_username.grid(row=0, column=0, padx=10, pady=10)
entry_username = tk.Entry(root)
entry_username.grid(row=0, column=1, padx=10, pady=10)
label_password = tk.Label(root, text="Password:")
label_password.grid(row=1, column=0, padx=10, pady=10)
entry_password = tk.Entry(root, show="")
# Entry widget for password, showing
entry_password.grid(row=1, column=1, padx=10, pady=10)
submit_button = tk.Button(root, text="Submit", command = submit_form)
submit_button.grid(row=2, column=0, columnspan=2, pady=10)
# Run the Tkinter event loop
root.mainloop()

You might also like