0% found this document useful (0 votes)
47 views16 pages

Python Unit 5

Uploaded by

garlapatikomal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
47 views16 pages

Python Unit 5

Uploaded by

garlapatikomal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 16

R20 PYTHON UNIT-5

V.K.R, V.N.B & A.G.K COLLEGE OF ENGINEERING::GUDIVADA


(Approved by AICTE, New Delhi & Affiliated to JNTUK, Kakinada)
An ISO 9001:2015 Certified Institute
Gudivada , Krishna District, Andhra Pradesh - 521301

UNIT:5

Errors and Exceptions:


As human beings, we commit several errors. A software developer is also a human being and hence prone to
commit errors wither in the design of the software or in writing the code. The errors in the software are called
‘bugs’ and the process of removing them are called ‘debugging’. In general, we can classify errors in a program
into one of these three types:
a) Compile-time errors
b) Runtime errors
c) Logical errors

Compile-time errors
These are syntactical errors found in the code, due to which a program fails to compile. For example, forgetting a
colon in the statements like if, while, for, def, etc. will result in compile-time error.

Example: A Python program to understand the compile-time error.


a=1
if a == 1
print("hello")

Output:
File ex.py, line 3
If a == 1
^
SyntaxError: invalid syntax

Runtime errors
When PVM (Python Virtual Machine) cannot execute the byte code, it flags runtime error. For example,
insufficient memory to store something or inability of PVM to execute some statement come under runtime
errors. Runtime errors are not detected by the python compiler.

Example: A Python program to understand the compile-time error.


print("hai"+25)

Output:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
print("hai"+25)

TypeError: cannot concatenate 'str' and 'int' objects

Logical errors

These errors depict flaws in the logic of the program. The programmer might be using a wrong formula of the
design of the program itself is wrong. Logical errors are not detected either by Python compiler of PVM.

Example: A Python program to increment the salary of an employee by 15%.


VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 PYTHON UNIT-5

Sal=150
00
Inc=500
Sal=Inc
print("Salary after Increment is", Sal)

Output:
Salary after Increment is 500
From the above program the formula for salary is wrong, because only the increment but it is not adding it tothe
original salary. So, the correct formula would be:
sal = sal + Inc

Exceptions:
 An exception is a runtime error which can be handled by the programmer.
 That means if the programmer can guess an error in the program and he can do something to eliminate the
harm caused by that error, then it is called an ‘exception’.
 All exceptions are represented as classes in python. The exceptions which are already available in python are
called ‘built-in’ exceptions. The base class for all built-in exceptions is ‘BaseException’ class.
 From BaseException class, the sub class ‘Exception’ is derived. From Exception class, the sub classes
‘StandardError’ and ‘Warning’ are derived.
 All errors (or exceptions) are defined as sub classes of StandardError. An error should be compulsory handled
otherwise the program will not execute.
 Similarly, all warnings are derived as sub classes from ‘Warning’ class. A warning represents a caution and
even though it is not handled, the program will execute. So, warnings can be neglected but errors cannot
neglect.

Exception Handling:

 The purpose of handling errors is to make the program robust. The word ‘robust’ means ‘strong’. A robust
 program does not terminate in the middle.
 Also, when there is an error in the program, it will display an appropriate message to the user and continue
execution.
 Designing such programs is needed in any software development.
 For that purpose, the programmer should handle the errors. When the errors can be handled, they arecalled
exceptions.

To handle exceptions, the programmer should perform the following four steps:

Step 1: The programmer should observe the statements in his program where there may be a possibility of
exceptions. Such statements should be written inside a ‘try’ block. A try block looks like as follows:

try:
statements

The greatness of try block is that even if some exception arises inside it, the program will not be terminated.
When PVM understands that there is an exception, it jumps into an ‘except’ block.
Step 2: The programmer should write the ‘except’ block where he should display the exception details to the user.
This helps the user to understand that there is some error in the program. The programmer should also display a
message regarding what can be done to avoid this error. Except block looks like as follows:

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 PYTHON UNIT-5

except exceptionname:
statements

The statements written inside except block are called ‘handlers’ since they handle the situation when theexception
occurs.
Step 3: If no exception is raised, the statements inside the ‘else’ block is executed. Else block looks like as
follows:

else:
statements

Step 4: Lastly, the programmer should perform clean up actions like closing the files and terminating any other
processes which are running. The programmer should write this code in the finally block. Finally block looks like
as follows:

finally:
statements

The specialty of finally block is that the statements inside the finally block are executed irrespective of whether
there is an exception or not. This ensures that all the opened files are properly closed and all the running
processes are properly terminated. So, the data in the files will not be corrupted and the user is at the safe-side.
Here, the complete exception handling syntax will be in the following format:

try:
statements
except
Exception1:
statements
except
Exception2:
statements
else:
statements
finally:
statements

 The following points are followed in exception handling:


 A single try block can be followed by several except blocks.
 Multiple except blocks can be used to handle multiple exceptions.
 We cannot write except blocks without a try block.
 We can write a try block without any except blocks.
 else block and finally blocks are not compulsory.
 When there is NO exception, else block is executed after try block.
 Finally block is always executed.

Example:

try:
a=float(input("Enter a value: "))
b=float(input("Enter b value: "))
c=a/b
except ZeroDivisionError:
print("Division with Zero is not possible") except ValueError:
print("Values should be either integer/float")
else:
print("Division is",c)finally:
print("Logout")

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 PYTHON UNIT-5

Output-1:
Enter a value: 52
Enter b value: 0
Division with Zero is not possibleLogout

Output-2:
Enter a value: x
Values should be either integer/floatLogout

Output-3:
Enter a value: 5
Enter b value: 2
Division is 2.5
Logout

List of Standard Exceptions:


Exception Name Description
Exception Base class for all exceptions
StopIteration Raised when the next() method of an
iterator does not point to any object.
SystemExit Raised by the sys.exit() function.
StandardError Base class for all built-in exceptions
except StopIteration and SystemExit
ArithmeticError Base class for all errors that occur for
numeric calculation
OverflowError Raised when a calculation exceeds
maximum limit for a numeric type.
ZeroDivisionError Raised when division or modulo by zero
takes place for all numeric types.
AssertionError Raised in case of failure of the Assert
statement.
AttributeError Raised in case of failure of attribute
reference or assignment.
EOFError Raised when there is no input from
either the raw_input() or input()
function and the end of file is reached.
ImportError Raised when an import statement fails.
KeyboardInterrupt Raised when the user interrupts
program execution, usually by pressing
Ctrl+c.
LookupError Base class for all lookup errors.
IndexError Raised when an index is not found in a
sequence.
KeyError Raised when the specified key is not
found in the dictionary
SyntaxError Raised when there is an error in Python
syntax.
SystemExit Raised when Python interpreter is quit
by using the sys.exit() function. If not
handled in the code, causes the
interpreter to exit
TypeError Raised when an operation or function is
attempted that is invalid for the
specified data type.
ValueError Raised when the built-in function for a
data type has the valid type of
arguments, but the arguments have
invalid values specified
VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 PYTHON UNIT-5

Raising an Exception
You can raise exceptions in several ways by using the raise statement. The general syntax for the raise
statement is as follows.

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

Here, Exception is the type of exception (For example, NameError) and argument is a value for the exception
argument. The argument is optional; if not supplied, the exception argument is None.
For Example, If you need to determine whether an exception was raised but don’t intend to handle it, a simpler
form of the raise statement allows you to re-raise the exception:

try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
raise

User-Defined Exceptions:
 Just like the exceptions which are already available in python language, a programmer can also create his own
exceptions, called ‘user-defined’ exceptions.
 When the programmer wants to create his own exception class, he should derive his class from Exception class
and not from ‘BaseException’ class.
 But, there may be some situations where none of the exceptions in Python are useful for the programmer.In
that case, the programme has to create his/her own exception and raise it.
 For example, let’s take an ATM where customers have accounts. Each account is characterized should by
account number and withdraw amount.
 The rule of the ATM is that every customer should withdraw only multiples of 100s.
 The programmer now is given a task to check the withdrawn amount which is multiple of 100s or not.
 So, the programmer wants an exception that is raised when the withdrawn amount in is not multiple of
 100. Since there is NO such exception available in python, the programme has to create his/her own exception.

For this purpose, he/she has to follow these steps:

1. Since all exceptions are classes, the programme is supposed to create his own exception as a class. Also, he
should make his class as a sub class to the in-built ‘Exception’ class.

class MyException(Exception):
def init (self, arg):
self.msg = arg

Here, MyException class is the sub class for ‘Exception’ class. This class has a constructor where a
variable‘msg’ is defined. This ‘msg’ receives a message passed from outside through ‘arg’.

The programmer can write his code; maybe it represents a group of statements or a function. When the
programmer suspects the possibility of exception, he should raise his own exception using ‘raise’ statement
as:

raise MyException(‘message’)

Here, raise statement is raising MyException class object that contains the given ‘message’.

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 PYTHON UNIT-5

1. The programmer can insert the code inside a ‘try’ block and catch the exception using ‘except’ block as:

try:
code
except MyException as me:
print(me.msg)

Here, the ‘me.msg’ contains the message given in the raise statement. All these steps are shown in
belowprogram.

Example:

class MyException(Exception):
def init (self, arg):
self.msg = arg
def check(amount):
if amount%100!=0:
raise MyException("Withdraw amount should be 100s only ")
try:
amount=int(input("Enter withdrawn amount: "))
check(amount)
print("Withdrawn Success")
except MyException as me:
print(me.msg)

Output-1:
Enter withdrawn amount: 500
Withdrawn Success
Output-2:
Enter withdrawn amount: 543
Withdraw amount should be 100s only

Graphical User Interfaces(GUI)


Introduction
Most modern computer software employs a graphical user interface or GUI. A GUI displays text as
well as small images (called icons) that represent objects such as directories, files of different types,
command buttons, and dropdown menus. In addition to entering text at keyboard, the user of a GUI
can select an icon with pointing device, such as mouse, and move that icon around on the display.

The Behavior of Terminal-Based Programs and GUI-Based Programs


• Two different versions of the bouncy program from a user’s point of view

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 PYTHON UNIT-5

 Both programs perform exactly the same function – However, their behavior, or look and feel, from a user’s
perspective are quite different.
 Problems: – User is constrained to reply to a definite sequence of prompts for inputs
 Once an input is entered, there is no way to change it – To obtain results for a different set of input data, user
must wait for command menu to be displayed again
 At that point, the same command and all of the other inputs must be re-entered – User can enter an
unrecognized command

The GUI-Based Version


 Uses a window that contains various components – Called window objects or widgets
 Solves problems of terminal-based version: Title bar, A label, An entry field, A commandbutton.
 Event-Driven Programming : User-generated events (e.g., mouse clicks) trigger operations inprogram to
respond by pulling in inputs, processing them, and displaying results.

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 PYTHON UNIT-5

Coding phase:
 Define a new class to represent the main window
 Instantiate the classes of window objects needed for this application (e.g., labels,command buttons).
 Position these components in the window.
 Instantiate the data model and provide for the display of any default data in the windowobjects .
 Register controller methods with each window object in which a relevant event might occur.
 Define these controller methods.

Define a main that launches the GUI.Coding Simple GUI-Based Programs

There are many libraries and toolkits of GUI components available to the Python programmer –tkinter includes classes
for windows and numerous types of window objects.

Create GUI applications


First, we will import Tkinter package and create a window and set its title:
from tkinter import *
window = Tk()
window.title("Welcome to tkinter")
window.mainloop()

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.

Create 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)
So the complete code will be like this:
from tkinter
import *window =
Tk()
lbl=Label(window,text="Hello)
lbl.grid(column=0, row=0)
window.mainloop()
You can set the label font so you can make it bigger and maybe bold. You can also change
thefont style. To do so, you can pass the font parameter like this:
lbl = Label(window, text="Hello", font=("Arial Bold",

50))Setting window size

We can set the default window size using geometry function like this:
window.geometry('350x200')
The above line sets the window width to 350 pixels and the height to 200 pixels.

Adding a button

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)
Get input using Entry class (Tkinter textbox)
You can create a textbox using Tkinter Entry class like
this:txt = Entry(window,width=10)

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 PYTHON UNIT-5

Then you can add it to the window using grid function as


usual. from tkinter import *
window = Tk() window.geometry('350x200')
lbl1 = Label(window, text="enterthefirstvalue")
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=10)txt3.grid(column=2, row=1)
def clicked():
res=int(txt1.get())+int(txt2.get())
txt3.insert(0,"result is {}".format(res))
btn = Button(window, text="Click Me", command=clicked)
btn.grid(column=2, row=0)
window.mainloop()
The above code creates a window with 2 labels, 3 text fields and reads two numbers from the
user and finally displays the result in the third text field.

Add a combobox
To add a combobox widget, you can use the Combobox class from ttk library like
this:from tkinter import *
combo = Combobox(window)
from tkinter import *
window = Tk()
window.geometry('350x200')
combo = Combobox(window)
combo['values']= (1, 2, 3, 4, 5, "Text")
combo.current(1) #set the selected item
combo.grid(column=0, row=0)
window.mainloop()
To get the selected item, you can use the get function like this:
combo.get()

Add a Checkbutton (Tkinter checkbox)


To create a checkbutton, you can use Checkbutton class like
this:
chk = Checkbutton(window, text='Choose')
the following program creates a check box. from tkinter import *
from tkinter.ttk import *
window = Tk() window.geometry('350x200')
chk_state = BooleanVar()
chk_state.set(True) #set check state
chk = Checkbutton(window, text='Choose', var=chk_state)
chk.grid(column=0, row=0)
window.mainloop()
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.

Add radio buttons widgets


To add radio buttons, simply you can use RadioButton class like this:
rad1 = Radiobutton(window,text='First', value=1)
Note that you should set the value for every radio button with a different value, otherwise, they
won’t work.

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 PYTHON UNIT-5

from tkinter import *


from tkinter.ttk
import *window =
Tk()
window.geometry('350x200')
rad1 = Radiobutton(window,text='First', value=1)
rad2 = Radiobutton(window,text='Second',
value=2) rad3 = Radiobutton(window,text='Third',
value=3) rad1.grid(column=0, row=0)
rad2.grid(column=1,
row=0)
rad3.grid(column=2,
row=0)
window.mainloop()

Create a MessageBox
To show a message box using Tkinter, you can use messagebox library like
this:
from tkinter import *
window = Tk()
window.geometry('350x200')
def clicked():
messagebox.showinfo('Message title', 'Message content')
btn = Button(window,text='Click here', command=clicked)
btn.grid(column=0,row=0)
window.mainloop()
You can show a warning message or error message the same way. The only thing that needs to be
changed is the message function.

Show warning and error messages


You can show a warning message or error message the same way. The only thing that needs to be
changed is the message function
messagebox.showwarning('Message title', 'Message content') #shows warning message
messagebox.showerror('Message title', 'Message content')
You can choose the appropriate message style according to your needs. Just replace the showinfo
function line from the previous line and run it.

Show askquestion dialogs


To show a yes no message box to the user, you can use one of the following messagebox
functions:
from tkinter import messagebox
res = messagebox.askquestion('Message title','Message content')
res = messagebox.askyesno('Message title','Message content')
res = messagebox.askyesnocancel('Message title','Message content')
res = messagebox.askokcancel('Message title','Message content')
res = messagebox.askretrycancel('Message title','Message content')

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

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 PYTHON UNIT-5

Add a SpinBox (numbers widget)


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.
Also, you can specify the width of the widget using the width parameter:
spin = Spinbox(window, from_=0, to=100, width=5

Other Useful Gui Resources In Python:-


For application developers, it is important to know the frameworks on which the application is built on.
Python programming language offers different kinds of frameworks to enable application development.
These frameworks are preferred by the developers to build both .apk and .exe applications. Here are 4 GUI
frameworks for Python that you should know about.

Kivy
This is the most preferred Python GUI framework which is used for computer and mobile applications. It is
an Open GL framework that comes in the form of a third-party library. This library contains various features
to help developers build robust applications for their system.

Tkinter
This is a famous library in Python apps development world. The GUI framework comes embedded with Python. There
is no need to separately install the same. The library is used to build GUI applications for computers. Tkinter
framework is for those who are new to Python.

PyQT
PyQT is an amazing Python library used to build cross-platform applications both for computer and mobile. This
library comes under two versions that are paid and free. The main drawback of the free version. It supports Windows,
Mac, Linux, Zaurus, and Android.

PySide
This is another powerful Python GUI tool that is bonded with the Qt framework. This comes with a special feature,
allowing it to easily blend with PyQT 4. Developers can easily switch from
PyQT to PySide to build better applications. The library works on Windows, Linux, Mac,Android, and Maemo.

Introduction To Programming Concepts With Scratch:-


Using Scratch to Learn Programming Concepts
1. Sprites. The most important thing in any Scratch program are the sprites. ...
2. Sequences. In order to make a program in any programing language, you need to think throughthe sequence of
steps.
3. Iteration (looping) ...
4. Conditional statements. ...
5. Variables. ...
6. Lists (arrays) ...
7. Event Handling. ...
8. Threads.

Programming is a big part of computer science, and computer science is at the core of our computing curriculum.
Since programming is itself at the core of computer science, it’s worth taking some time to really get to grips with both
programming as a series of concepts and one of the main tools used in
schools to teach these concepts, Scratch.

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 PYTHON UNIT-5

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 in certain
ways like a jigsaw, eliminating the typing errors that tend to occur when people use
text-based programming languages.
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 Stage2 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
from some of my own Scratch projects, I have written here the main programming
concepts that can belearnt through the use of this application.

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 programing language, you need to think
through the sequence of steps.

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 PYTHON UNIT-5

Iteration (looping)

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


accomplished in Scratch usingthe 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, arescore and timer.
VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 PYTHON UNIT-5

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 onits own, but runs within a program. When
two threads launch at the same time it is called parallel
execution.
VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 PYTHON UNIT-5

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 anoher. A common example is when onesprite 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 storesthe 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.
VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 PYTHON UNIT-5

User interface design

Interactive user interfaces can be designed in Scratch using clickable sprites to


create buttons.

VKR,VNB&AGK COLLEGE OF ENGINEERING

You might also like