PWP UNIT 6
PWP UNIT 6
I/O Operations :
o Printing to screen :
The simplest way to produce output is using the print statement where
you can pass zero or more expressions separated by commas. This
function converts the expressions you pass into a string and writes the
result to standard output as follows.
Example :
Print “Hello World”
The raw_input :
Function The raw_input([prompt]) function reads one line from
standard input and returns it as a string.
>>> str = raw_input("Enter your input: ")
Enter your input: mmpolytechnic
>>> print(str)
mmpolytechnic
>>>
Mrs. K. G. Raut
>>> str = input("Enter your input: ")
Enter your input: 1
>>> print(str)
File Handling :
Mrs. K. G. Raut
1. f=open(“ABC”,”a”)
2. f.write(“Python is a programming language”)
3. f=open(“purva”,”r”)
4. print(f.read())
o Closing a file
Python automatically closes a file when the reference object of a file is
reassigned to another file. It is a good practice to use the close() method to
close a file.
f=open(“purva”,”r”)
print(f.read(1))
f.close()
The rename()
method takes two arguments, the current filename and the new filename.
import os
os.rename(“TY”,”SY”)
import os
os.remove(“SY”)
Exception Handling :
An exception can be defined as an abnormal condition in a program
resulting in the disruption in the flow of the program. Python provides us
with the way to handle the Exception so that the other part of the code
Mrs. K. G. Raut
can be executed without any disruption. However, if we do not handle the
exception, the interpreter doesn't execute all the code that exists after that.
In Python, there are several built-in exceptions that can be raised when an
error occurs during the execution of a program. Here are some of the most
common types of exceptions in Python:
SyntaxError: This exception is raised when the interpreter encounters a
syntax error in the code, such as a misspelled keyword, a missing colon, or
an unbalanced parenthesis.
TypeError: This exception is raised when an operation or function is
applied to an object of the wrong type, such as adding a string to an integer.
NameError: This exception is raised when a variable or function name is
not found in the current scope.
IndexError: This exception is raised when an index is out of range for a
list, tuple, or other sequence types.
KeyError: This exception is raised when a key is not found in a dictionary.
ValueError: This exception is raised when a function or method is called
with an invalid argument or input, such as trying to convert a string to an
integer when the string does not represent a valid integer.
AttributeError: This exception is raised when an attribute or method is
not found on an object, such as trying to access a non-existent attribute of a
class instance.
IOError: This exception is raised when an I/O operation, such as reading
or writing a file, fails due to an input/output error.
ZeroDivisionError: This exception is raised when an attempt is made to
divide a number by zero.
ImportError: This exception is raised when an import statement fails to
find or load a module.
Mrs. K. G. Raut
Try and Except Statement – Catching Exceptions
Try and except statements are used to catch and handle exceptions in Python.
Statements that can raise exceptions are kept inside the try clause and the
statements that handle the exception are written inside except clause.
In Python, exceptions can be handled using a try statement. A try block
consisting of one or more statements is used by programmers to partition code
that might be affected by an exception.
A critical operation which can raise exception is placed inside the try
clause and the code that handles exception is written in except clause.
The associated except blocks are used to handle any resulting exceptions
thrown in the try block. That is we want the try block to succeed and if it
does not succeed, we want to control to pass to the catch block.
If any statement within the try block throws an exception, control
immediately shifts to the catch block. If no exception is thrown in the try
block, the catch block is skipped.
There can be one or more except blocks. Multiple except blocks with
different exception names can be chained together.
The except blocks are evaluated from top to bottom in the code, but only
one except block is executed for each exception that is thrown.
The first except block that specifies the exact exception name of the
thrown exception is executed. If no except block specifies a matching
exception name then an except block that does not have an exception
name is selected, if one is present in the code.
For handling exception in Python, the exception handler block needs to
be written which consists of set of statements that need to be executed
according to raised exception. There are three blocks that are used in the
exception handling process, namely, try, except and finally.
1. try Block:
A set of statements that may cause error during runtime are
to be written in the try block.
2. except Block:
It is written to display the execution details to the user when
certain exception occurs in the program. The except block executed
only when a certain type as exception occurs in the execution of
Mrs. K. G. Raut
statements written in the try block.
3. else block:
If no exception was raised in the try block, this block is
executed. It's useful for code that should run only if everything went
smoothly.
4. finally Block:
This is the last block written while writing an exception handler in
the program which indicates the set of statements that many use to
clean up to resources used by the program.
Syntax:
try:
D the operations here
......................
except Exception1:
If there is Exception1, then execute this block.
except Exception2:
If there is Exception2, then execute this block.
......................
else:
If there is no exception then execute this block.
Example 2 :
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
Mrs. K. G. Raut
print("You can't divide by zero.")
except ValueError:
print("Please enter a valid number.")
else:
print(f"Result is {result}")
finally:
print("Program completed.")
Raise Statement :
The raise keyword is used to raise an exception.
You can define what kind of error to raise, and the text to print to
the user.
o Example :
try:
age = int(input("Enter the age: "))
if age < 18:
raise ValueError("Age must be 18 or older.")
else:
print("The age is valid.")
except ValueError as e:
print(f"Invalid input: {e}")
Mrs. K. G. Raut
Except ValueError:
Print(“The age is not valid”)
Output :
Enter the Age ? 2
The age is not valid
Step 1 : Create user defined Exception class exception and inherit from an in-
built exception class.
Class YOurException(Exception):
Example :
a=5
b=0
try :
k=int(input(“enter e number”))
print(k)
Mrs. K. G. Raut
print(“ file open “)
print(a/b)
except ZeroDivisionError as e :
print(“you cannot divide a number by zero”,e)
except ValueError as e :
print(“Invalid Input”)
except Exception :
print(“something went wrong”)
Finally :
Print(“file Closed”)
Mrs. K. G. Raut