Python Unit 5
Python Unit 5
UNIT:5
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.
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.
Output:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
print("hai"+25)
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.
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:
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
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")
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
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.
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.
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’.
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
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
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.
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.
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",
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)
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()
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.
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.
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.
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.
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.
Iteration (looping)
Conditional statements
Variables
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
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