Unit V
Unit V
S.Gayathri
Assistant Professor
Department of Computer science and Engineering
Jerusalem College of Engineering
UNIT V FILES EXCEPTIONS AND GUI
,
Files: Basic file operations and access methods . Errors and Exceptions:
Syntax Errors, Exception types ,Handling Exceptions, Raising Exceptions,
Simple graphics: simple 2D drawing shapes and coloring. GUI using
Tkinter.
FILES:
• A file can be defined as a location for storing related data.
• A file holds a specific name for itself.
• A file can be a sequence of bits, bytes, lines or records depending on
the application used to create it.
Example:
sample.py, student.txt
Here sample, student are the file names with file extensions
Types of files:
Text files:
• A text file is a file containing characters structured as individual lines
of text.
• In addition to printable characters, text files also contain the non
printing new line character \n to denote the end of each text line
Binary files:
• Binary files can contain various types of data, such as numerical
values. These are not structured as lines of text.
• Such files can only be read and written via a computer program
Different Modes to Open a File in Python
FILE OPERATIONS:
1.Opening a file
2.Reading from a file
3.Writing to a file
4.Appending a file
5.Closing a file
Opening a file
➢All files must be opened first before they can be used.
➢In python, when a file is opened, a file object is created that provides
methods for accessing the file.
➢ In python there is a built in function open() to open a file.
Syntax:
file_object=open(filename,accessmode)
Closing a file
fp=open("new.txt","r")
print(fp.read())
fp.close()
Output:
This file is closed
Closing a file using with:
A file can also closed using with the statement as follows:
Syntax:
with open(“filename”,accessmode) as fileobject:statements for file
operations
Example:
with open("new.txt","r") as fp:print(fp.read())
fp.close()
Output:
This file is closed
ERRORS AND EXCEPTIONS
There are two kinds of errors:
syntax errors and exceptions.
Syntax Errors
• Syntax errors, also known as parsing errors.
• Syntax error is an error in the syntax of a sequence of characters or
tokens that is intended to be written in python. For compiled
languages, syntax errors are detected at compile-time. A program will
not compile until all syntax errors are corrected.
• For interpreted languages, however, a syntax error may be detected
during program execution, and an interpreter's error messages might
not differentiate syntax errors from errors of other kinds.
Exceptions
• Even if a statement or expression is syntactically correct, it may cause
an error when an attempt is made to execute it. Errors detected
during execution are called exceptions.
• You will soon learn how to handle them in Python programs. Most
exceptions are not handled by programs, however, result in error
messages as shown here:
>>> 55+(5/0)
Traceback (most recent call last):
File "<pyshell#12>", line 1, in
<module> 55+(5/0)
Zero DivisionError: integer division or modulo by zero
>>> 5+ repeat*2
Traceback (most recent call last):
File "<pyshell#13>", line 1, in
<module> 5+ repeat*2
NameError: name 'repeat' is not defined
>>> '5'+5
Traceback (most recent call last):
File "<pyshell#14>", line 1, in
<module> '5’+5
TypeError: cannot concatenate 'str' and 'int' objects
Exception Handling Clauses
HANDLING EXCEPTIONS
• Python provides two very important features to handle any
unexpected error in your
Python programs and to add debugging capabilities in them.
Exception Handling:
• An exception is an event, which occurs during the execution of a
program that disrupts the normal flow of the program's instructions.
• In general, when a Python script encounters a situation that it cannot
cope with, it raises an exception.
• When a Python script raises an exception, it must either handle the
exception immediately otherwise it terminates and quits.
• If you have some suspicious code that may raise an exception, you
can defend your program by placing the suspicious code in a try: block.
After the try: block, include an except: statement, followed by a block
of code which handles the problem.
Python Exception clause
Try Except Finally clause
• The try block lets you test a block of code for errors.
• The except block lets you handle the error.
• The finally block lets you execute code, regardless of the result of the
try- and except blocks.
Example
The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")
Output:
exception occurred
Example
This statement will raise an error, because x is not defined:
print(x)
Output:
Traceback (most recent call last):
File "demo_try_except_error.py", line 3, in <module>
print(x)
NameError: name 'x' is not define
Many Exceptions
• You can define as many exception blocks as you want, e.g. if you want to
execute a special block of code for a special kind of error:
Example
• Print one message if the try block raises a NameError and another for other
errors:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Output:
Variable x is not defined
Else
You can use the else keyword to define a block of code to be executed if no
errors were raised:
Example
In this example, the try block does not generate any error:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Output:
Hello
Nothing went wrong
Finally
The finally block, if specified, will be executed regardless if the try block
raises an error or not.
Example
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Output:
Something went wrong
The 'try except' is finished
Raise an exception
As a Python developer you can choose to throw an exception if a
condition occurs.To throw (or raise) an exception, use the raise
keyword.
Example:
Raise an error and stop the program if x is lower than 0:
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
Output:
Traceback (most recent call last):
File "demo_ref_keyword_raise.py", line 4, in <module>
raise Exception("Sorry, no numbers below zero")
Exception: Sorry, no numbers below zero
You can define what kind of error to raise, and the text to print to the
user.
Example
Raise a TypeError if x is not an integer:
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
Output:
Traceback (most recent call last):
File "demo_ref_keyword_raise2.py", line 4, in <module>
raise TypeError("Only integers are allowed")
TypeError: Only integers are allowed
User defined Exception:
• Python has many built-in exceptions.
• However, sometimes you may need to create custom exceptions that
serves your purpose.
• In Python, users can define such exceptions by creating a new class.
This exception class has to be derived, either directly or indirectly, from
Exception class. Most of the built-in exceptions are also derived form
this class
>>> class CustomError(Exception):
... pass
...
>>> raise CustomError
Traceback (most recent call last):
...__main__.CustomError
>>> raise CustomError("An error occurred")
Traceback (most recent call last):
...
__main__.CustomError: An error occurred
OUTPUT
Enter a number: 12
This value is too large, try again!
Enter a number: 0
This value is too small, try again
Enter a number: 10
Congratulations! You guessed it correctly.
Simple Graphics
• turtle is a Python library to draw graphics.
• After we import turtle we can give commands likeforward, backward, right,
left etc.
Simple Turtle Commands
➢ forward(10) → It moves the turtle (arrow) forward by 10 pixels.
➢ backward(5) → It moves the turtle (arrow) backward by 5 pixels
➢ right(35) → It moves the turtle (arrow) clockwise by an angle of 35
degrees.
➢ left(55) → It moves the turtle (arrow) counter-clockwise by an angle of 55
degrees
➢ goto(x,y) → It moves the turtle (arrow) to the position x, y
➢ dot() → It creates a dot in the current position.
➢ shape(‘circle’) → It draws a circle shape.
Examples
Draw a Star
appropriate steps is to move the cursor forward and then turn right
import turtle
star = turtle.Turtle()
for i in range(100):
star.forward(100)
star.right(144)
turtle.done()
Output:
Multiple Squares
multiple squares all starting from a common point.
forward, backward to draw line and left ,right for direction turn 90 degrees.
Example
import turtle
mult_square=turtle.Turtle()
def Multiple_Squares(length, colour):
mult_square.pencolor(colour)
mult_square.pensize(2)
mult_square.forward(length)
mult_square.right(90)
mult_square.forward(length)
mult_square.right(90)
mult_square.forward(length)
mult_square.right(90)
mult_square.forward(length)
mult_square.right(90)
mult_square.setheading(360)
for i in range(60,120,15):
Multiple_Squares(i,'blue')
turtle.done
Output:
2D-GRAPHICS-COLORS-SHAPES