Jcs2201-Python Programming Unit-V Notes
Jcs2201-Python Programming Unit-V Notes
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:
Files are named locations on disk to store related information. They are used to permanently store data in a non-
volatile memory (e.g. hard disk).
To read from or write to a file, first open the file. When read/write operation is done, file needs to be closed so that
the resources that are tied with the file are freed. Hence, in Python, a file operation takes place in the following
order:
Open a file
Read or write operation
Close the file
Text files:
A text file is usually considered as sequence of lines. Line is a sequence of characters (ASCII), stored on permanent non-
volatile memory (e.g. hard disk). In text file, each line is terminated by a special character, known as End of Line (EOL). Text files
are stored in human readable form. Text file can be viewed or edited in any text editor.
Examples of text file formats:
Example1:
str= "This is a String in Python"
fp = open( ‘fil1.txt’,"w+")
fp.write(str)
fp.close()
print(fp.closed)
Reading Information from a File:
To read a file, open the file in read mode. There are three ways in which we can read the files in python.
read([n])
readline([n])
readlines() – returns all lines to a list. Here, n is the number of bytes to be read.
Example 2:
fp = open(“C:/Documents/Python/test.txt”, “r”)
print(fp.read(5))
Output: Hello
Here the file test.txt is opened in read-only mode and fp.read(5) method reads the first 5 characters of the file.
Example 3:
fp = open(“C:/Documents/Python/test.txt”, “r”)
print(fp.read())
Output:
Hello World
Hello Python
Good Morning
How are you.
Here no argument is given inside the read() function. Hence it will read all the content present inside the file.
Example 4:
fp = open(“C:/Documents/Python/test.txt”, “r”)
print(fp.readline(2))
Output: He
This function returns the first 2 characters of the next line.
Example 5:
fp = open(“C:/Documents/Python/test.txt”, “r”)
print(fp.readline())
Output: Hello World
This function read the content of the file on a line by line basis.
Example 6:
fp = open(“C:/Documents/Python/test.txt”, “r”)
print(fp.readlines())
Output: [‘Hello World\n’, ‘Hello Python\n’, ‘Good Morning’]
This function reads all the lines present inside the text file including the newline characters.
Example 7:
Reading specific line from a File:
line_number = 4
fp = open(“C:/Documents/Python/test.txt”, ’r’)
currentline = 1
for line in fp:
if(currentline == line_number):
print(line)
break
currentline = currentline +1
Output: How are You
In the above example, the 4th line is read from the ‘test.txt’ file using “for loop”.
Example 8:
Reading the entire file:
filename = “C:/Documents/Python/test.txt”
f = open(filename, ‘r’)
filedata = f.read()
print(filedata)
Output:
Hello World
Hello Python
Good Morning
How are You
Example 1:
f = open(“C:/Documents/Python/test.txt”, “w”)
f.write(“Hello World”)
The above code writes the String ‘Hello World’ into the ‘test.txt’ file
Example 2:
mf = open(“C:/Documents/Python/test.txt”, “w”)
mf.write(“Hello World\n”)
mf.write(“Hello Python”)
The first line will be ‘Hello World’ and as \n character is mentioned, the cursor will move to the next line of the file and then write
‘Hello Python’. If \n character is not mentioned, then the data will be written continuously in the text file like ‘Hello World Hello
Python’
Example 3:
fruits = [“Apple\n”, “Orange\n”, “Grapes\n”, “Watermelon”]
f = open(“C:/Documents/Python/test.txt”, “w”)
f.writelines(fruits)
The above code writes a list of data into the ‘test.txt’ file simultaneously
Append in a Python File:
To append data into a file open the file in ‘a+’ mode to have access to both append and write modes.
Example 1:
m = open(“C:/Documents/Python/test.txt”, “a+”)
m.write (“Strawberry”)
The above code appends the string ‘Strawberry’ at the end of the ‘test.txt’ file
Example 2:
f= open(“C:/Documents/Python/test.txt”, “a+”)
f.write (“\nGuava”)
The above code appends the string ‘Apple’ at the end of the ‘test.txt’ file in a new line.
Exception Handling
Errors
Errors or mistake in a program is often referred to as bugs. Debugging is the process of finding and eliminating
errors. Errors can be classified into three major categories
1. Syntax errors
2. Runtime errors
3. Logical errors
Syntax errors, also known as parsing errors are identified by Python while parsing the program, It displays error message
and exit without continuing execution process. They are similar to spelling mistakes or grammar mistakes. Some common
Python syntax errors include:
leaving out a keyword
putting a keyword in the wrong place
leaving out a symbol, such as a colon, comma or brackets
misspelling a keyword
incorrect indentation
empty block
Logical errors occur due to mistake in program’s logic. Here program runs without any error messages, but produces an
incorrect result. These errors are difficult to fix. Here are some examples of mistakes which lead to logical errors
using the wrong variable name
indenting a block to the wrong level
using integer division instead of floating-point division
getting operator precedence wrong
making a mistake in a Boolean expression
off-by-one, and other numerical errors
Runtime error is an exception that occurs during the execution of a program. Examples of Python runtime errors are:
division by zero
performing an operation on incompatible types
using an identifier which has not been defined
accessing a list element, dictionary value or object attribute which doesn’t exist
trying to access a file which doesn't exist
TYPES OF EXCEPTION
There are two types of Exception:
Built-in Exception
User Defined Exception
i) Built-in Exception
There are some built-in exceptions which cannot be changed. The Syntax for Built-in Exception is:
except Exception_Name:
An Exception is an event which occurs during the execution of a program that disrupts the normal flow of the program’s instructions.
If a python script encounters a situation it cannot cope up, it raises an exception. There are four blocks which help to handle the
exception. They are :
try block
except statement
else block
finally block
Example:
(a,b) = (5,0)
try:
z=x/y
except ZeroDivisionError:
Print (“Divide by Zero”)
Output: Divide by Zero
`Exceptions come in different types, and the types printed as part of the message: the type in the example
is ZeroDivisionError which occurs due to division by 0. The string printed as the exception type is the name of the
built-in exception that occurred.
Example:
7. Default exception:
User-Defined Exception in Python: In this example, we will illustrate how user-defined exceptions can be used in a
program to raise and catch errors. This program will ask the user to enter a number until they guess a stored number
correctly. To help them figure it out, hint is provided whether their guess is greater than or less than the stored number.
number = 10
while True:
try:
num = int(input("Enter a number: "))
if num < number:
raise ValueTooSmallError
elif 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: 8
This value is too small, try again!
Enter a number: 10
Congratulations! You guessed it correctly.
2. Write python program to count number of words in a file. (Using Exception Handling)
try:
filename = ‘T.txt'
textfile = open(filename, ‘r’)
print(“The number of words are: “ + len(textfile.split(“ “)))
textfile.close()
except IOError:
print (‘Cannot open file %s for reading’, % filename)
import sys
sys.exit(0)
Output
The number of word are : 20
3. Write python program to count number of lines, words and characters in a text file.
count_line=0
count_word=0
count_character=0
f=open("sample.txt","r") for line in f:
words=line.split()
count_line +=1
count_word +=len(words)
count_character +=len(line)
print('No. of lines:', count_line)
print('No. of words:', count_word)
print('No. of characters:', count_character)
f.close()
There are many Python packages that can be used to create graphics and GUI’s. Two graphics modules, called turtle and
tkinter, come as a part of Python’s standard library. tkinter is primarily designed for creating GUI’s. In fact, IDLE is built using
tkinter. However, turtle module is primarily used as a simple graphics package but can also be used to create simple GUI’s. The turtle
module is an implementation of turtle graphics and uses tkinter for the creation of the underlying graphics
Using penup() and setposition() to move the turtle without making a line
>>> t.penup()
>>> t.setposition(100, -100)
>>> t.pendown()
>>> t.fd(130)
Result of moving the turtle without drawing a line and then, once at the new location, drawing a line.
Write a python program using turtle to draw different 2D drawing shapes and color them.
import turtle
def draw_circle(radius, color):
turtle.begin_fill()
turtle.color(color)
turtle.circle(radius)
turtle.end_fill()
radius = 50
length = 100
breadth = 200
turtle.speed(2)
draw_circle(radius, "magenta")
draw_square(length, "red")
turtle.penup()
turtle.goto(150, 0)
turtle.pendown()
draw_rectangle(length, breadth, "green")
draw_triangle(length, "black")
t urtle.exitonclick()
tkinter window
S. Options Description
No
1 anchor Specifies the exact position of the text. The default value is CENTER, which is used
to center the text within the specified space.
2 bg The background color displayed behind the widget.
3 bitmap To set the bitmap to the graphical object specified so that, the label can represent
the graphics instead of text.
4 bd Represents the width of the border. The default is 2 pixels.
5 cursor The mouse pointer will be changed to the type of the cursor specified, i.e., arrow,
dot, etc.
6 font font type of the text written inside the widget.
7 fg The foreground color of the text written inside the widget.
8 height Specifies the height of the widget.
9 image The image that is to be shown as the label.
10 justify To represent the orientation of the text if the text contains multiple lines. It can be
set to LEFT, RIGHT, and CENTER justification.
11 padx Horizontal padding of the text. The default value is 1.
12 pady Vertical padding of the text. The default value is 1.
13 relief The type of the border. The default value is FLAT.
14 text Set to the string variable which contain one or more line of text.
15 textvariable The text written inside the widget is set to the control variable StringVar so that it
can be accessed and changed accordingly.
16 underline To display a line under the specified letter of the text. Set this option to the number
of the letter under which the line will be displayed.
17 width The width of the widget specified as number of characters.
18 wraplength Instead of having only one line as the label text, can break it to the number of lines
where each line has the number of characters specified to this option.
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)
m.mainloop()
Example:
import Tkinter as tk
m=tk.Tk()
but = tk. Button(m, text="Click me!", width=25,height=5, bg=”blue”, fg=”yellow”)
m.mainloop()
3. Input With Entry Widgets: displays text box where user can type texts. Creating and styling an Entry widget works
pretty much exactly like Label and Button widgets.
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()
Output:
5. RadioButton: 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 checkbuttons.
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()
Output:
6. MenuButton is 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()
Output:
In the above example, when “File” is clicked a dropdown menu appears as “New file”, “Save”, and “Save as” else
“File” is only on the window.
7. Frame: is a rectangular region on the screen to implement complex widgets and to organize a group of
widgets.
Example1
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()
Output:
Example2
import Tkinter as tk
m=tk.Tk()
frme1 = tk.Frame(m, width=200, height=100, bg=”red”)
frme1.pack(fill=tk.BOTH, side=tk.LEFT, expand=True)
frme2 = tk.Frame(m, width=100, height=100, bg=”yellow”)
frme2.pack(fill=tk.BOTH, side=tk.LEFT, expand=True)
frme3 = tk.Frame(m, width=50, height=100, bg=”blue”)
frme3.pack(fill=tk.BOTH, side=tk.LEFT, expand=True)
m.mainloop()
1. Create a simple registration form using Tkinter
import tkinter as tk
from tkinter import messagebox
def submit_form():
username = entry_username.get()
password = entry_password.get()
messagebox.showinfo("Registration Successful", f"Welcome, {username}!")
root = tk.Tk()
root.title("Registration Form")
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_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)
root.mainloop()