PP_UNIT-5
PP_UNIT-5
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.
• 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\VAHIDA>python excep.py
enter numerator1
enter denominator0
Traceback (most recent call last):
File "excep.py", line 3, in <module>
quo=num/den
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:
Output:
Numerator: 10
Denominator: 0
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.
e.g.
Here, Exception is the name of exception to be raised (example, TypeError). 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.
e.g.
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.
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
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:
print(“user defined exception generated with value”,e.val)
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
–
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 –
Operator
Button
Canvas
Check button
Entry
Frame
Label
List box
. Menu button
Menu
Message
Radio button
Scale
Scrollbar
Text
Top level
.
Spin box
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.
Example:
class App:
def __init__(self,master):
frame=Frame(master)
frame.pack()
self.button=Button(frame,text="QUIT",fg="red",command=frame.quit)
self.button.pack(side=LEFT)
self.hi=Button(frame,text="Hello",fg="red",command=self.say_hi)
self.hi.pack(side=LEFT)
def say_hi(self):
root=Tk()
app=App(root)
root.mainloop()
Turtle methods
forward()
backward()
back()
right()
left()
goto()
setpos()
setposition()
setx()
sety()
setheading()
circle
()
dot()
undo()
speed()
color()
pencolor()
fillcolor()
begin_fill()
end_fill()
reset()
clear()
write()
onclick()
onrelease()
ondrag()
Example Program:
Example 2:
Program:
done()
output:
Example 3:
Program:
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!
Sequences
In order to make a program in any programming language, you need to think through the
sequence of steps.
Iteration (looping)
Conditional statements
A variable stores specific information. The most common variables in computer games
for example, are score and timer.
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.
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.
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.