PWP - Chapter 6 PDF
PWP - Chapter 6 PDF
• Python provides two built-in functions to read a line of text from standard
input, which by default comes from the keyboard. These functions are −
1. input(prompt)
2. input()
• The input([prompt]) function allows user input. It takes one argument. The
syntax is as follows:
Syntax:
input(prompt)
Example:
print(‘Hello ’ + x)
Output−
• The input() function always evaluate the input provided by user and return
same type data. The syntax is as follows:
Syntax:
x=input()
Example:
x=int(input())
print(type(x))
Output−
5
Vishal Chavre
<class 'int'>
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 –
• The syntax is
Print(object(s),separator=separator,end=end,file=file,flush=flush)
Parameter values:
Example
Example
Output:
• To make the output more attractive formatting is used. This can be done by
using the str.format() method.
Example
a=10
b=20
Value of a is 10 and b is 20
Example
a=12.3456789
print('Value of x is=%3.2f'%a)
print('Value of x is=%3.4f'%a)
Output:
Value of x is=12.35
Value of x is=12.3457
File Handling:
What is a file?
• Since, random access memory (RAM) is volatile which loses its data when
computer is turned off, we use files for future use of the data.
• When we want to read from or write to a file we need to open it first. When
we are done, it needs to be closed, so that resources that are tied with the file
are freed.
Open a file
• Python has a built-in function open() to open a file. This function returns a
file object, also called a handle, as it is used to read or modify the file
accordingly.
• We can specify the mode while opening a file. In mode, we specify whether
we want to read 'r', write 'w' or append 'a' to the file. We also specify if we
want to open the file in text mode or binary mode.
• The default is reading in text mode. In this mode, we get strings when
reading from the file.
• On the other hand, binary mode returns bytes and this is the mode to be
used when dealing with non-text files like image or exe files.
• Before you can read or write a file, you have to open it using Python's built-
in open() function. This function creates a file object, which would be
utilized to call other support methods associated with it.
Vishal Chavre
Syntax
• access_mode − The access_mode determines the mode in which the file has
to be opened, i.e., read, write, append, etc. This is optional parameter and
the default file access mode is read (r).
(**if any question asked on this topic for 4 marks write only modes for text
mode and skip modes for binary format)
• r
Opens a file for reading only. The file pointer is placed at the beginning of the file.
This is the default mode.
• rb
Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file. This is the default mode.
• r+
Opens a file for both reading and writing. The file pointer placed at the beginning
of the file.
• rb+
Opens a file for both reading and writing in binary format. The file pointer placed
at the beginning of the file.
• w
Opens a file for writing only. Overwrites the file if the file exists. If the file does
not exist, creates a new file for writing.
• wb
Opens a file for writing only in binary format. Overwrites the file if the file exists.
If the file does not exist, creates a new file for writing.
• w+
Opens a file for both writing and reading. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing.
• wb+
Opens a file for both writing and reading in binary format. Overwrites the
existing file if the file exists. If the file does not exist, creates a new file for reading
and writing.
• a
Opens a file for appending. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist, it creates a
new file for writing.
• ab
Opens a file for appending in binary format. The file pointer is at the end of the
file if the file exists. That is, the file is in the append mode. If the file does not
exist, it creates a new file for writing.
Vishal Chavre
• a+
Opens a file for both appending and reading. The file pointer is at the end of the
file if the file exists. The file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.
• ab+
Opens a file for both appending and reading in binary format. The file pointer is
at the end of the file if the file exists. The file opens in the append mode. If the file
does not exist, it creates a new file for reading and writing.
Example-
print(f.read())
Output-
Hello
Example:
fo = open("F:\\2019-2020\\PYTH prog\\README.txt","w)
Output:
Opening mode : w
• file.isatty() -It returns true if file has a <tty> (teletypewriter for deaf)
attached to it.
Vishal Chavre
Reading data from files:
The read() Method-
• The read() method reads a string from an open file. It is important to note
that Python strings can have binary data. apart from text data.
Syntax
fileObject.read([count])
Here, passed parameter is the number of bytes to be read from the opened file.
This method starts reading from the beginning of the file and if count is missing,
then it tries to read as much as possible, maybe until the end of file.
Example
fo = open("F:\\2019-2020\\PYTH prog\\README.txt","r
str=fo.read(5);
print(fo.read(3))
print(fo.read())
fo.close()
Output-
Wo
rld
The readline() Method-
• The readline() method output the entire line whereas readline(n) outputs at
most n bytes of a single line of a file.
• Once the end of line is reached, we get empty string on further reading.
Syntax
fileObject.readline([count])
Here, passed parameter is the number of bytes of a single line to be read from the
opened file.
Example
fo = open("F:\\2019-2020\\PYTH prog\\README.txt","r")
print(fo.readline())
print(fo.readline(3))
print(fo.readline())
print(fo.readline())
print(fo.readline())
Output-
The readline() method output the entire line whereas readline(n) outputs at most n
bytes of a single line of a file.
Onc
Syntax
fileObject.readline([count])
Vishal Chavre
Syntax
fileObject.readlines()
Example
fo = open("F:\\2019-2020\\PYTH prog\\README.txt","r")
print(fo.readlines())
Output-
Writing Files:
There are two ways to write in a file.
e.g.
fo = open("README.txt","w+")
fo.write("Hello World\n")
fo = open("README.txt","r")
print(fo.read())
Output:
Hello World
File_object.writelines(L)
e.g.
L=["str1\n","str2\n","str3\n"]
fo = open("README.txt","w+")
fo.writelines(L)
fo = open("README.txt","r")
print(fo.read())
Output:
str1
str2
str3
Closing a File:
When we are done with operations to the file we need to properly close the file.
Closing a file will free up the resources that were tied with the filed and is done
using python close() method.
# Program closing a file
fo = open("README.txt")
fo.close()
Output:
We can change the current file cursor(position) using the seek() method. Similarly
the tell() method returns the current position(in number of bytes) of the cursor.
print(fo.tell())
print(fo.read())
print(fo.tell())
print(fo.read())
print(fo.seek(0))
print(fo.read())
Output:
str1
str2
str3
18
str1
str2
str3
Renaming a File:
• Renaming a file in python is done with the help of rename() method. To
rename a file in python the OS module needs to be imported.
The rename() method takes two arguments, the current filename and the new
filename.
Syntax
os.rename(current_filename, new_filename)
import os
os.rename("README.txt","newREADME.txt")
Output
Deleting a File:
• We can use the remove() method to delete files by supplying the name of
the file to be deleted as the argument.
Syntax
os.remove(filename)
# Program for removing files
import os
os.remove(“myfile.txt")
Output
Directories in Python:
• If there is large number of files to handle in python program, we can arrange
the code within different directories to make things more manageable.
• A directory or folder is a collection of files and sub directories. Python has
the OS module, which provides us with many useful methods to work with
directories.
• This method takes in the path of the new directory. If the full path is not
specified, the new directory is created in the current working directory.
e.g.
import os
os.mkdir("testdir")
• We can get the present working directory using the getcwd() method.
• This method returns the current working directory in the form of a string.
e.g.
import os
print(os.getcwd())
Changing Directory:
• We can change the current working directory using the chdir() method.
• The new path that we want to change to must be supplied as a string to this
method. We can use both forward slash (/) or the backward slash (\) to
separate path elements.
Vishal Chavre
Example-
import os
print(os.getcwd())
os.chdir("F:\\2019-2020")
print(os.getcwd())
Output:
F:\2019-2020\PYTH prog
F:\2019-2020
• All files and sub directories inside a directory can be known using
the listdir() method.
• This method takes in a path and returns a list of sub directories and files in
that path. If no path is specified, it returns from the current working
directory.
e.g.
import os
print(os.listdir())
Removing Directory:
import os
os.rmdir("testdir")
PROGRAMS
if f=='x':
exit()
else:
c=open(f,'w+')
sent1=str(input())
c.write(sent1)
c=open(f,'r')
print(c.read())
Hello
Hello
# Program to open a file in write mode and append some content at the end of
a file
if f=='x':
exit()
else:
c=open(f,'a+')
sent1=str(input())
c.write("\n")
c.write(sent1)
c=open(f,'r')
print(c.read())
Output:
World
World
file = open("Test.txt","r")
for i in file:
for c in i:
if c == char:
count = count + 1
Output:
Vishal Chavre
ENTER CHARACTER : o
Exception Handling:
Introduction-
When we execute a python program there may be a few uncertain conditions
which occur, known as errors. There are three types of errors.
Compile Time Error- Occurs at the time of compilation due to violation of syntax
rules like missing of a colon.
Run Time Error- Occurs during the runtime of a program due to wrong input
submitted to the program by user.
• An exception is also called as runtime error that can halt the execution of
the program.
• Python has many built-in exceptions which forces your program to output
an error when something in it goes wrong.
• When these exceptions occur, it causes the current process to stop and
passes it to the calling process until it is handled. If not handled, our
program will crash.
• If never handled, an error message is spit out and our program come to a
sudden, unexpected halt.
• There are three blocks that are used in the exception handling process,
namely try, except and finally.
try Block- A set of statements that may cause error during runtime are to be
written in the try block.
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 statements written
in the try block.
finally Block- This is the last block written while writing an exception
handler in the program which indicates the set of statements that are used to
clean up the resources used by the program.
Vishal Chavre
Exception Handling in Python:
‘try : except’ statement-
• In Python, exceptions can be handled using a try statement.
• A critical operation which can raise exception is placed inside the try clause
and the code that handles exception is written in except clause.
randomList = ['a', 0, 2]
try:
r = 1/int(entry)
break
except:
print(sys.exc_info()[0],"occured.")
print("Next entry.")
print()
Output:
The entry is a
<class 'ValueError'> occured.
Next entry.
The entry is 0
Next entry.
The entry is 2
• This is not a good programming practice as it will catch all exceptions and
handle every case in the same way. We can specify which exceptions an
except clause will catch.
• A try clause can have any number of except clause to handle them
differently but only one will be executed in case an exception occurs.
Example pseudocode-
try:
# do something
pass
exceptValueError:
Vishal Chavre
# handleValueError exception
pass
pass
except:
pass
Example:
try :
a=3
if a < 4 :
b = a/(a-3)
print("Value of b = ", b)
Output:
n=10
m=0
try:
n/m
except ZeroDivisionError:
else:
print(n/m)
Output:
Vishal Chavre
try-except statement with no exception:
• We can use try-except clause with no exception.
• All types of exceptions that occur are caught by the try-except statement.
• However, because it catches all exceptions, the programmer cannot identify
the root cause of a problem that may occur. Hence this type of programming
approach is not considered good.
while True:
try:
div=10/a
break
except:
print("Error occured")
print()
Output:
Enter an integer: a
Error occured
Error occured
Please enter valid value
Enter an integer: 0
Error occured
Enter an integer: 5
try..finally statement:
• The try statement in Python can have an optional finally clause. This
clause is executed no matter what, and is generally used to release
external resources.
• In all these circumstances, we must clean up the resource once used, whether
it was successful or not. These actions (closing a file, GUI or disconnecting
from network) are performed in the finally clause to guarantee execution.
Example
try:
Vishal Chavre
f = open("test.txt",encoding = 'utf-8')
finally:
f.close()
• This type of construct makes sure the file is closed even if an exception
occurs
try:
result=x/y
except ZeroDivisionError:
print("Divison by Zero")
else:
finally:
Output:
Divison by Zero
• We can also optionally pass in value to the exception to clarify why that
exception was raised.
Example:
while True:
try:
if age<18:
else:
break
except Exception:
Output:
• However, sometimes you may need to create custom exceptions that serve
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 from
this class.
• User can also create and raise his/her own exception known as user defined
exception.
Example:
pass
class AgeSmallException(error):
pass
# main program
while True:
try:
raise AgeSmallException
else:
break
except AgeSmallException:
print()
Output:
class Error(Exception):
pass
class ValueTooSmallError(Error):
pass
class ValueTooLargeError(Error):
pass
# main program user guesses a number until he gets it right you need to guess
this number
number = 10
while True:
try:
if i_num< number:
raise ValueTooSmallError
raise ValueTooLargeError
elif i_num==number:
break
except ValueTooSmallError:
print()
except ValueTooLargeError:
print()
print("Correct number")
Output:
Enter a number: 5
Enter a number: 10
Correct number
Vishal Chavre
Vishal Chavre