0% found this document useful (0 votes)
20 views19 pages

PP_UNIT-5

Python

Uploaded by

Dwipendu Kundu
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)
20 views19 pages

PP_UNIT-5

Python

Uploaded by

Dwipendu Kundu
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/ 19

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,

File "1.py", line 2


while i<=10
^
SyntaxError: invalid syntax

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.

• However, such errors can be detected at the time of testing.


Exceptions:

• 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.

The syntax for try–except block can be given as

try:

statements

except ExceptionName:

statements

Example:

num=int(input(“Numerator: ”))

deno=int(input(“Denominator: “))

try:

quo=num/deno

print(“QUOTIENT: “,quo)

except ZeroDivisionError:

print(“Denominator can’t be zero”)

Output:

Numerator: 10
Denominator: 0

Denominator can’t be zero

Multiple except blocks:

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.

Multiple exceptions in single block:


Raising Exceptions:

You can Explicitly raise an exception using the raise keyword.

The general syntax for the raise statement is

raise [Exception [, args [, traceback]]]

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.

Defining clean-up actions(The finally Block)

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 and User-defined Exceptions:

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

EXCEPTION NAME DESCRIPTION


Exception Base class for all exceptions
ArithmeticError Base class for all errors that occur for numeric calculation.
OverflowError Raised when a calculation exceeds maximum limit for a numeric type.
FloatingPointErrorRaised when a floating point calculation fails.
ZeroDivisionError Raised when division or modulo by zero takes place for all numeric types.
Raised when there is no input from either the raw_input() or input()
EOFError function
and the end of file is reached.
ImportError Raised when an import statement fails.
Raised when the user interrupts program execution, usually by pressing
KeyboardInterrupt
Ctrl+c.
IndexError Raised when an index is not found in a sequence.
KeyError Raised when the specified key is not found in the dictionary.
NameError Raised when an identifier is not found in the local or global namespace.
IOError Raised when an input/ output operation fails
SyntaxError Raised when there is an error in Python syntax.
IndentationError Raised when indentation is not specified properly.

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:
print(“user defined exception generated with value”,e.val)

Graphical User Interface:

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

• Import the Tkinter module.


• Create the GUI application main window.
• Add one or more of the above-mentioned widgets to the GUI application.
• Enter the main event loop to take action against each event triggered by the user.

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

Standard attributes for widgets


• Dimensions
• Colors
• Fonts
• Relief styles
• Bitmaps
• Cursors

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:

from tkinter import *

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):

print("hai every one")

root=Tk()

app=App(root)

root.mainloop()

turtle — Turtle graphics


Introduction

Turtle graphics is a popular way for introducing programming to kids. Imagine a


robotic turtle starting at (0, 0) in the x-y plane. Give it the command turtle.forward(15), and it
moves (on-screen!) 15 pixels in the direction it is facing, drawing a line as it moves. Give it
the command turtle.left(25), and it rotates in-place 25 degrees clockwise.
By combining together these and similar commands, intricate shapes and
pictures can easily be drawn.

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:

from turtle import *


t=Turtle()
t.color("green")
for i in range(4):
t.circle(30)
t.left(30)
t.color("blue")
t.circle(30)
t.left(30)
t.color("red")
t.circle(30)
t.left(30)
t.color("green")

done()

output:

Example 3:
Program:

from turtle import *


def draw_rectangle():
for i in range(4):
t.forward(50)
t.left(90)
t=Turtle()
for i in range(36):
draw_rectangle()
t.left(10)
done()
output:

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!

Sequences

In order to make a program in any programming language, you need to think through the
sequence of steps.
Iteration (looping)

Iteration simply refers to the repetition of a series of instructions. This is accomplished in


Scratch using the repeat, repeat until or forever blocks.

Conditional statements

A conditional statement is a set of rules performed if a certain condition is met. In


Scratch, the if and if-else blocks check for a condition.
Variables

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.

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.

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.

You might also like