Python Programming - Unit-5
Python Programming - Unit-5
EXCEPTION HANDLING
Errors and Exceptions:The programs that we write may behave abnormally or unexpectedly
because of some errors and/or exceptions.
Errors:
• The two common types of errors that we very often encounter are syntax errors and logic
errors.
Syntax errors: And syntax errors, arises due to poor understanding of the language. Syntax
errors occur when we violate the rules of Python and they are the most common kind of
error that we get while learning a new language.
Example :
i=1 while
i<=10
print(i) i=i+1
if you run this program we will get syntax error like below,
Logical errors: While logic errors occur due to poor understanding of problem and its
solution. Logic error specifies all those type of errors in which the program executes but
gives incorrect results. Logical error may occur due to wrong algorithm or logic to solve
a particular program.
WWW.JNTUKNOTES.COM 1
• Even if a statement is syntactically correct, it may still cause an error when executed. • Such
errors that occur at run-time (or during execution) are known as exceptions. • An exception
is an event, which occurs during the execution of a program and disrupts the normal flow of
the program's instructions.
• Exceptions are run-time anomalies or unusual conditions (such as divide by zero, accessing
arrays out of its bounds, running out of memory or disk space, overflow, and underflow)
that a program may encounter during execution.
• Like errors, exceptions can also be categorized as synchronous and asynchronous
exceptions.
• While synchronous exceptions (like divide by zero, array index out of bound, etc.) can be
controlled by the program
• Asynchronous exceptions (like an interrupt from the keyboard, hardware malfunction, or
disk failure), on the other hand, are caused by events that are beyond the control of the
program.
• When an exception occurs in a program, the program must raise the exception. After that it
must handle the exception or the program will be immediately terminated. • if exceptions
are not handled by programs, then error messages are generated..
Example:
num=int(input("enter numerator"))
den=int(input("enter denominator"))
quo=num/den print(quo)
output:
C:\Users\PP>python excep.py enter
numerator1
enter denominator0
WWW.JNTUKNOTES.COM 2
ZeroDivisionError: division by zero
Handling Exceptions:
We can handle exceptions in our program by using try block and except block. A critical
operation which can raise exception is placed inside the try block and the code that handles
exception is written in except block.
try:
statements except
ExceptionName:
statements
Example:
num=int(input(“Numerator: ”))
deno=int(input(“Denominator: “))
try:
quo=num/deno
print(“QUOTIENT: “,quo)
except ZeroDivisionError:
Numerator: 10
Denominator: 0
Denominator can’t be zero
WWW.JNTUKNOTES.COM 3
Python allows you to have multiple except blocks for a single try block. The block
which matches with the exception generated will get executed. syntax:
try:
You do your operations here;
...................... except(Exception1[,
Exception2[,...ExceptionN]]]): If there is any
exception from the given exception list, then
execute this block.
......................
else:
If there is no exception then execute this block.
String:") try:
print(string+num)
except TypeError as e:
print(e)
except ValueError as e:
print(e)
(OR)
string = input("Enter a String:")
try:
num = int(input("Enter a
number")) print(string+num)
except (TypeError,ValueError) as e:
print(e)
WWW.JNTUKNOTES.COM 4
OUTPUT :
>>>
Enter a String:hai
Enter a number3
Can't convert 'int' object to str implicitly
>>>
Enter a String:hai
Enter a numberbye invalid literal for
int() with base 10: 'bye'
Raising Exceptions:
The raise keyword is used to raise an exception.You can define what kind of error to raise,
and the text to print to the user.
The raise statement allows the programmer to force a specific exception to occur. The sole
argument in raise indicates the exception to be raised. This must be either an exception instance or
an exception class (a class that derives from Exception)
Here, Exception is the name of exception to be raised. args is optional and specifies a value for
the exception argument. If args is not specified, then the exception argument is None. The final
argument, traceback, is also optional and if present, is the traceback object used for the exception.
num=int(input("enter numerator"))
den=int(input("enter denominator")) try:
quo=num/den
print(quo)
except ZeroDivisionError:
WWW.JNTUKNOTES.COM 5
print("Denominator cant be zero")
OUTPUT:
>>> enter
numerator4 enter
denominator0
>>> enter
numerator4 enter
denominator2
The finally block is always executed before leaving the try block. This means that the
statements written in finally block are executed irrespective of whether an exception has
occurred or not. Syntax:
try:
Write your operations here
......................
Due to any exception, operations written here will be skipped
finally:
This would always be executed.
......................
e.g.
num=int(input("enter numerator"))
den=int(input("enter denominator"))
try:
WWW.JNTUKNOTES.COM 6
quo=num/den
print(quo)
except ZeroDivisionError:
finally:
print("TASK DONE")
OUTPUT:
>>> enter
numerator4 enter
denominator2
2.0
TASK DONE
>>> enter
numerator4 enter
denominator0
TASK DONE
WWW.JNTUKNOTES.COM 7
Built-in Exceptions:
Exceptions that are already defined in python are called built in or pre-defined exception.
In the table listed some built-in exceptions
DESCRIPTION
EXCEPTION
NAME
ArithmeticError Base class for all errors that occur for numeric calculation.
OverflowError Raised when a calculation exceeds maximum limit for a numeric type.
ZeroDivisionErro Raised when division or modulo by zero takes place for all numeric types.
r
EOFError
Raised when there is no input from either the raw_input() or input()
function and the end of file is reached.
KeyboardInterrupt Raised when the user interrupts program execution, usually by pressing
Ctrl+c.
NameError Raised when an identifier is not found in the local or global namespace.
WWW.JNTUKNOTES.COM 8
User –defined exception:
Python allows programmers to create their own exceptions by creating a new exception
class. The new exception class is derived from the base class Exception which is predefined in
python. Example:
class myerror(Exception):
def __init__(self,val):
self.val=val
try:
raise myerror(10)
except myerror as e:
OUTPUT:
user defined exception generated with value 10
UNIT 5
Python provides various options for developing graphical user interfaces (GUIs). Most
important are listed below.
• Tkinter
• wxPython
• JPython
Tkinter Programming
Tkinter is the standard GUI library for Python. Python when combined with Tkinter
provides a fast and easy way to create GUI applications. Creating a GUI application using
Tkinter is an easy task. All you need to do is perform the following steps –
WWW.JNTUKNOTES.COM 9
Example:
From import Tkinter *
top = Tkinter.Tk()
# Code to add widgets will go here...
top.mainloop()
This would create a following window –
Tkinter Widgets:
Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI
application. These controls are commonly called widgets.
There are currently 15 types of widgets in Tkinter. We present these widgets as well as
a brief description in the following table – • Button
• Canvas
• Check button
• Entry
• Frame
• Label
• List box
• Menu button
• Menu
• Message
• Radio button
• Scale
• Scrollbar
• Text
• Top level.
• Spin box
WWW.JNTUKNOTES.COM 10
• Paned Window
• Label Frame
• Tk Message Box
Geometry Management:
All Tkinter widgets have access to specific geometry management methods, Tkinter exposes
the following geometry manager classes: pack, grid, and place. •
• The pack() Method - This geometry manager organizes widgets in blocks before placing
them in the parent widget.
• The grid() Method - This geometry manager organizes widgets in a table-like
structure in the parent widget.
• The place() Method -This geometry manager organizes widgets by placing them in a
specific position in the parent widget.
1) Creation of a window/widget
First, we will import Tkinter package and create a window and set its title. The last line which calls
mainloop function, this function calls the endless loop of the window, so the window will wait for
any user interaction till we close it. If you forget to call the mainloop function, nothing will appear
to the user.
Program:
from tkinter import * window =
Tk() window.title("Welcome to
tkinter") window.mainloop()
WWW.JNTUKNOTES.COM 11
2) Creating a window with specific dimensions and a label
To add a label to our previous example, we will create a label using the label class like this: lbl
= Label(window, text="Hello")
Then we will set its position on the form using the grid function and give it the location like this:
lbl.grid(column=0, row=0)
Program
from tkinter import * window = Tk()
window.geometry("500x600") window.title("CSE") lbl =
Label(window, text="HelloWorld",font=("Arial Bold", 50))
lbl.grid(column=0, row=0) window.mainloop()
WWW.JNTUKNOTES.COM 12
3)Adding a Button to window/widget
Let’s start by adding the button to the window, the button is created and added to the window the
same as the label:
btn = Button(window, text="Click Me")
btn.grid(column=1, row=0)
Program:
from tkinter import * window = Tk()
window.geometry("300x300")
window.title("CSE") lbl =
Label(window, text="HelloWorld")
lbl.grid(column=0, row=0) btn =
Button(window, text="Click Me")
btn.grid(column=1, row=0)
window.mainloop()
WWW.JNTUKNOTES.COM 13
4)Creating 2 text fields to enter 2 numbers, and a button when clicked gives sum of the 2
numbers and displays it in 3rd text field
You can create a textbox using Tkinter Entry class like this:
= Entry(window,width=10)
Then you can add it to the window using grid function as usual
Program:
from tkinter import * window = Tk()
window.geometry('350x200') lbl1 = Label(window,
text="enter the first value") lbl1.grid(column=0,
row=0) lbl2 = Label(window, text="enter the
second value") lbl2.grid(column=0, row=1) txt1 =
Entry(window,width=10) txt1.grid(column=1,
row=0) txt2 = Entry(window,width=10)
txt2.grid(column=1, row=1) txt3 =
Entry(window,width=20) txt3.grid(column=1,
row=2) def clicked():
res=int(txt1.get())+int(txt2.get())
txt3.insert(0,"Sum is {}".format(res))
WWW.JNTUKNOTES.COM 14
btn = Button(window, text="Click Me",
command=clicked) btn.grid(column=2, row=1)
window.mainloop()
WWW.JNTUKNOTES.COM 15
5) Creating 2 checkboxes
To create a checkbutton, you can use Checkbutton class like this:
chk = Checkbutton(window, text='Choose')
Here we create a variable of type BooleanVar which is not a standard Python variable, it’s a
Tkinter variable, and then we pass it to the Checkbutton class to set the check state as the
highlighted line in the above example. You can set the Boolean value to false to make it
unchecked. the following program creates a check box.
WWW.JNTUKNOTES.COM 16
the following program creates a check box
WWW.JNTUKNOTES.COM 17
window.geometry('350x200')
def clicked():
messagebox.showinfo('Message title ', 'Message content')
# messagebox.showerror('Message title ', 'Message content')
# messagebox.show('Message title ', 'Message content') btn =
Button(window,text='Click here', command=clicked)
btn.grid(column=0,row=0) window.mainloop()
WWW.JNTUKNOTES.COM 18
8) Creating various message boxes
To show a yes no message box to the user, you can use one of the following messagebox
Functions.
• If you click OK or yes or retry, it will return True value, but if you choose no or cancel, it
will return False.
• The only function that returns one of three values is askyesnocancel function, it returns
True or False or None.
9) Creating a Spinbox
To create a Spinbox widget, you can use Spinbox class like this:
spin = Spinbox(window, from_=0, to=100)
Here we create a Spinbox widget and we pass the from_ and to parameters to specify the
numbers range for the Spinbox.
from tkinter import * window = Tk()
window.title("Welcome to tkinter") spin =
Spinbox(window, from_=0, to=100)
spin.grid(column=0,row=0)
window.mainloop()
WWW.JNTUKNOTES.COM 19
Introduction to programming concepts of scratch
Programming is core of computer science, it’s worth taking some time to really get to grips with
programming concepts and one of the main tools used in schools to teach these concepts, Scratch.
Programming simply refers to the art of writing instructions (algorithms) to tell a computer what
to do. Scratch is a visual programming language that provides an ideal learning environment for
doing this. Originally developed by America’s Massachusetts Institute of Technology, Scratch is
a simple, visual programming language. Colour coded blocks of code simply snap together. Many
media rich programs can be made using Scratch, including games, animations and interactive
stories. Scratch is almost certainly the most widely used software for teaching programming to
Key Stage 2 and Key Stage 3 (learners from 8 to 14 years).
Scratch is a great tool for developing the programming skills of learners, since it allows all manner
of different programs to be built. In order to help develop the knowledge and understanding that
go with these skills though, it’s important to be familiar with some key programming concepts that
underpin the Scratch programming environment and are applicable to any programming language.
Using screenshots, we will understand the scratch concepts.
Sprites
The most important thing in any Scratch program are the sprites. Sprites are the graphical
objects or characters that perform a function in your program. The default sprite in Scratch is the
cat, which can easily be changed. Sprites by themselves won’t do anything of course, without
coding!
WWW.JNTUKNOTES.COM 20
Sequences
In order to make a program in any programming language, you need to think through the
sequence of steps.
Iteration (looping)
WWW.JNTUKNOTES.COM 21
Conditional statements
Variables
A variable stores specific information. The most common variables in computer games
for example, are score and timer.
WWW.JNTUKNOTES.COM 22
Lists (arrays)
A list is a tool that can be used to store multiple pieces of information at once.
Event Handling
When key pressed and when sprite clicked are examples of event handling. These blocks
allow the sprite to respond to events triggered by the user or other parts of the program.
Threads
A thread just refers to the flow of a particular sequence of code within a program. A thread
cannot run on its own, but runs within a program. When two threads launch at the same time it is
called parallel execution.
WWW.JNTUKNOTES.COM 23
Coordination & Synchronisation
The broadcast and when I receive blocks can coordinate the actions of multiple sprites.
They work by getting sprites to cooperate by exchanging messages with one another. A common
example is when one sprite touches another sprite, which then broadcasts a new level.
Keyboard input
This is a way of interacting with the user. The ask and wait prompts users to type. The
answer block stores the keyboard input.
WWW.JNTUKNOTES.COM 24
Boolean logic
Boolean logic is a form of algebra in which all values are reduced to either true or false.
The and, or, not statements are examples of Boolean logic.
User interface design
Interactive user interfaces can be designed in Scratch using clickable sprites to create
buttons.
WWW.JNTUKNOTES.COM 25
1) Creation of a window/widget from
window.title("Welcome to tkinter")
window.mainloop()
WWW.JNTUKNOTES.COM 26
2) Creating a window with specific
lbl.grid(column=0, row=0)
window.mainloop()
window.geometry("300x300")
window.title("CSE") lbl =
Label(window, text="HelloWorld")
lbl.grid(column=0, row=0)
window.mainloop()
WWW.JNTUKNOTES.COM 27
4)Creating 2 text fields to enter 2 numbers, and a button when clicked gives sum of the 2
numbers and displays it in 3rd text field from tkinter import * window = Tk()
res=int(txt1.get())+int(txt2.get())
row=1) window.mainloop()
WWW.JNTUKNOTES.COM 28
5) Creating 2 checkboxes from tkinter import * from
window.mainloop()
window.geometry('350x200') rad1 =
Radiobutton(window,text='Third', value=3)
window.mainloop()
WWW.JNTUKNOTES.COM 29
7) Creating a message box on clicking a
command=clicked) btn.grid(column=0,row=0)
window.mainloop()
WWW.JNTUKNOTES.COM 30
8) Creating various message boxes from
messagebox.askquestion('Message title','Message
messagebox.askyesnocancel('Message
messagebox.askokcancel('Message
messagebox.askretrycancel('Message
title','Message content')
WWW.JNTUKNOTES.COM 31
WWW.JNTUKNOTES.COM 32
9) Creating a Spinbox from tkinter import
to=100) spin.grid(column=0,row=0)
window.mainloop()
WWW.JNTUKNOTES.COM 33