0% found this document useful (0 votes)
6 views20 pages

PWP S24

This document is a model answer paper for the Summer 2024 examination on Programming with Python, provided by the Maharashtra State Board of Technical Education. It includes important instructions for examiners, various questions on Python programming concepts, and their corresponding model answers. The content covers data structures, operators, syntax, and examples related to Python programming, aimed at assessing students' understanding and application of the subject matter.

Uploaded by

sangharaj5252
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views20 pages

PWP S24

This document is a model answer paper for the Summer 2024 examination on Programming with Python, provided by the Maharashtra State Board of Technical Education. It includes important instructions for examiners, various questions on Python programming concepts, and their corresponding model answers. The content covers data structures, operators, syntax, and examples related to Python programming, aimed at assessing students' understanding and application of the subject matter.

Uploaded by

sangharaj5252
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

PYTHON

MODEL ANSWER PAPER S24

This Study Material is provided by Campusify.co.in ©


We have wide range of study materials of Diploma and Engineering,

#We are building Biggest Community of Diploma Students and if you


want to be a part of it for multiple benefits then join our community by
following links.

Our Site - https://www.campusify.co.in/


Join Telegram Channel - https://t.me/campusifyy
Join Whatsapp Grp- https://tinyurl.com/Join-Campusify-Whatsapp
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
SUMMER – 2024 EXAMINATION
Model Answer – Only for the Use of RAC Assessors

Subject Name: Programming with Python Subject Code:


22616
Important Instructions to examiners:
1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner may try to assess the
understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more Importance (Not applicable for
subject English and Communication Skills.
4) While assessing figures, examiner may give credit for principal components indicated in the figure. The figures drawn
by candidate and model answer may vary. The examiner may give credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant values may vary and
there may be some difference in the candidate’s answers and model answer.
6) In case of some questions credit may be given by judgement on part of examiner of relevant answer based on
candidate’s understanding.
7) For programming language papers, credit may be given to any other program based on equivalent concept.
8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi and Bilingual (English +
Marathi) medium is introduced at first year of AICTE diploma Programme from academic year 2021-2022. Hence if
the students in first year (first and second semesters) write answers in Marathi or bilingual language (English
+Marathi), the Examiner shall consider the same and assess the answer based on matching of concepts with model
answer.

Q. Sub Answer Marking


No. Q. Scheme
N.

1 Attempt any FIVE of the following: 10 M

a) Enlist any four data structures used in python. 2M

Ans Data structures used in python are: 2M


1) List (Any 4
2) Set correct data
3) Tuple structures
4) Dictionary name)
5) Frozen Sets
b) Give membership operators in python. 2M

Ans Membership operators are: 1M


In: Give result true if value is found in list or in sequence, and give result false if item is
not in list or in sequence (for each
Not in: Give result true if value is not found in list or in sequence, and give result false if Membership
Operators)
item is in list or in sequence.
c) Write syntax for a method to sort a list. 2M

Ans Syntax of sort method for a list: 2 M for


list.sort(reverse=True|False, key=myFunc) correct
Were, syntax

Page No: 1 | 19
Campusify - Free Study Material - https://t.me/campusifyy
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
reverse (Optional): for reverse=True, it will sort the list descending. Default is
reverse=False
key (Optional): A function to specify the sorting criteria.
d) Write use of matplotlib package in python. 2M

Ans Use of matplotlib package in python: 1M


1) Matplotlib is use for creating static, animated, and interactive visualizations in
Python. (for each
2) It is used along with NumPy to provide an environment that is an effective open- use of
source alternative for MATLAB. matplotlib
3) Matplotlib can be used in Python scripts, the Python and IPython shell, web package)
application servers, and various graphical user interface toolkits like Tkinter,
awxPython, etc.

e) What is data abstruction and data hiding. 2M

Ans Data abstraction: Data Abstraction is used to hide the internal functionality of the 1M
function from the users. The users only interact with the basic implementation of the
function, but inner working is hidden. User is familiar with that "what function (for
does" but they don't know "how it does." definition of
data
Data hiding: Data hiding is a concept which underlines the hiding of data or information abstraction
from the user. Data hiding is a software development technique specifically used in and data
Object-Oriented Programming (OOP) to hide internal object details (data members). hiding)
Data hiding includes a process of combining the data and functions into a single unit to
conceal data within a class by restricting direct access to the data from outside the class.

f) Write the syntax of fopen. 2M

Ans Syntax of fopen: 2 M for


f=open(filename, mode) correct
Were, syntax
filename: This parameter as the name suggests, is the name of the file that we want to
open.
mode: This parameter is a string that is used to specify the mode in which the file is to be
opened.

g) What is dictionary? 2M

Ans Dictionary is an unordered collection of key-value pairs. 2 M for


OR correct
In Python, dictionaries are mutable data structures that allow you to store key-value pairs. explanation
Dictionary can be created using the dict() constructor or curly braces' {}'. of
dictionary

Page No: 2 | 19
Campusify - Free Study Material - https://t.me/campusifyy
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
2. Attempt any THREE of the following: 12 M

a) Explain with example: 4M


i) Indentation
ii) Variables
Ans i) Indentation: For each
• Python provides no braces to indicate blocks of code for class and function correct
definitions or flow control. explanation
• Blocks of code are denoted by line indentation, which is compulsory. and
• The number of spaces in the indentation is variable, but all statements within Example – 2
the block must be indented the same amount. M

Figure of Indentation
• Example:
if True:
print "True"
else:
print "False"
• Thus, in Python all the continuous lines indented with same number of spaces
would form a block.
ii) Variables:
• Python Variable is containers that store values.
• We do not need to declare variables before using them or declare their type.
• A variable is created the moment we first assign a value to it.
• A Python variable is a name given to a memory location.
• It is the basic unit of storage in a program.
• Variable Naming Rules in Python
1) Variable name should start with letter(a-z ,A-Z) or underscore (_).
Example: age, _age, Age
2) In variable name, no special characters allowed other than underscore (_).
Example: age_, _age
3) Variables are case sensitive.
Example: age and Age are different, since variable names are case
sensitive.
4) Variable name can have numbers but not at the beginning.
Example: Age1
5) Variable name should not be a Python reserved keyword.
• Example:

Page No: 3 | 19
Campusify - Free Study Material - https://t.me/campusifyy
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
x = 5 # x is of type integer
y = "John" # y is of type string
b) Print the following pattern using loop: 4M
1010101
10101
101
1
Ans p = '1' 4M
q = '0' (for any
j=0 correct
k=4 program
while k >= 1: with proper
print(" "*j + (k-1)*(p+q) +p+ " "*j) logic)
k = k-1
j=j+1
c) Write python program to perform following operations on set. 4M

i) Create set of five elements.

ii) Access set elements.

iii) Update set by adding one element.

iv) Remove one element from set.

Ans i) Create set of five elements 1M


set1 = {11, 22, 33,44,55} (each for
ii) Access set elements correct
print("\nElements of set: ") operations
for i in set1: on set )
print(i)
iii) Update set by adding one element
set1.add(88)
iv) Remove one element from set.
set1.discard(44)
Or
set1.remove(44)
d) Describe following Standard Packages 4M

i) Numpy

ii) Pandas

Ans i) Numpy 2M
(for each

Page No: 4 | 19
Campusify - Free Study Material - https://t.me/campusifyy
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
• NumPy is the fundamental package for scientific computing with Python. correct
NumPy stands for "Numerical Python". It provides a high-performance explanation)
multidimensional array object, and tools for working with these arrays.
• An array is a table of elements (usually numbers), all of the same type,
indexed by a tuple of positive integers and represented by a single variable.
NumPy's array class is called ndarray. It is also known by the alias array.
• In NumPy arrays, the individual data items are called elements. All elements
of an array should be of the same type. Arrays can be made up of any
number of dimensions.
• In NumPy, dimensions are called axes. Each dimension of an array has a
length which is the total number of elements in that direction.
• The size of an array is the total number of elements contained in an array in
all the dimension. The size of NumPy arrays are fixed; once created it cannot
be changed again.
• Numpy arrays are great alternatives to Python Lists. Some of the key
advantages of Numpy arrays are that they are fast, easy to work with, and
give users the opportunity to perform calculations across entire arrays.

Figure shows the axes (or dimensions) and lengths of two example arrays;
(a) is a one-dimensional array and (b) is a two-dimensional array.

ii) Panda
• Pandas is a powerful and versatile library that simplifies the tasks of data
manipulation in Python.
• Pandas is well-suited for working with tabular data, such as spreadsheets or
SQL tables.
• The Pandas library is an essential tool for data analysts, scientists, and
engineers working with structured data in Python.
• It is built on top of the NumPy library which means that a lot of the
structures of NumPy are used or replicated in Pandas.
• The data produced by Pandas is often used as input for plotting functions in
Matplotlib, statistical analysis in SciPy, and machine learning algorithms in
Scikit-learn.

Page No: 5 | 19
Campusify - Free Study Material - https://t.me/campusifyy
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
3. Attempt any THREE of the following: 12 M

a) What is the output of the following program? 4M

dict1={'Google': 1, 'Facebook': 2, 'Microsoft': 3}

dict2={'GFG': 1, 'Microsoft': 2, 'Youtube': 3}

dict1.update(dict2);

for key, values in dictl-items():

print (key, values)

Ans Google 1 4 M for


correct
Facebook 2 output
Microsoft 2
GFG 1
Youtube 3

b) Write a python program that takes a number and checks whether it is a 4M


palindrome.

Ans def is_palindrome(num): 2 M for


logic,
original_num = num
2 M for
reverse_num = 0 correct
program
while num > 0:
digit = num % 10
reverse_num = (reverse_num * 10) + digit
num //= 10
return original_num == reverse_num
number = 12321
if is_palindrome(number):
print(f"{number} is a palindrome.")
else:
print(f"{number} is not a palindrome.")

Page No: 6 | 19
Campusify - Free Study Material - https://t.me/campusifyy
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
Output: 12321 is a palindrome.

c) Write a python program to create a user defined module that will ask your 4M
program name and display the name of the program.

Ans User Defined Module- ProgramName.py 4 M for


correct
def pName(str): program.
print("Name of program is : ",str)

Main program- Program.py


import ProgramName
str=input("Enter program name: ")
ProgramName.pName(str)
Output-
Enter program name: Program
Name of program is : Program

d) List data types used in python. Explain any two with example. 4M

Ans Python has various standard data types that are used to define the operations possible on 2 M for
them and the storage method for each of them. Data types in Python programming types,
includes:
2 M for two
1. Numbers: Represents numeric data to perform mathematical operations.
proper
2. String: Represents text characters, special symbols or alphanumeric data. examples

3. List: Represents sequential data that the programmer wishes to sort, merge etc.
4. Tuple: Represents sequential data with a little difference from list.
5. Dictionary: Represents a collection of data that associate a unique key with each value.
6. Boolean: Represents truth values (true or false).
Example1: Tuple Data Type
• Tuple is an ordered sequence of items same as list. The only difference is that tuples are
immutable. Tuples once created cannot be modified.
• Tuples are used to write-protect data and are usually faster than list as it cannot change
dynamically. It is defined within parentheses ( ) where items are separated by commas ( ,
).

Page No: 7 | 19
Campusify - Free Study Material - https://t.me/campusifyy
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
• A tuple data type in python programming is similar to a list data type, which also
contains heterogeneous items/elements.
Example: For tuple.
a=(10,'abc',1+3j)
print(a)
(10, 'abc', (1+3j))
Example 2:List Data Type
List is an ordered sequence of items. It is one of the most used datatype in Python and is
very flexible.

• List can contain heterogeneous values such as integers, floats, strings, tuples, lists and
dictionaries but they are commonly used to store collections of homogeneous objects.
• The list datatype in Python programming is just like an array that can store a group of
elements and we can refer to these elements using a single name.
• Declaring a list is pretty straight forward. Items separated by commas ( , ) are enclosed
within brackets [ ].
Example:
For list.
first=[10, 20, 30]
# homogenous values in list
second=["One","Two","Three"]
Print(first)
[10, 20, 30]
Print(second)
['One', 'Two', 'Three']

4. Attempt any THREE of the following: 12 M

a) Compare list and tuple (any four points). 4M

Ans Sno. LIST TUPLE 1 M each


for one
1 Lists are mutable Tuples are immutable point.
4 M for 4

Page No: 8 | 19
Campusify - Free Study Material - https://t.me/campusifyy
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
The implication of iterations is The implication of iterations is correct
2
Time-consuming comparatively Faster points.

The list is better for performing


A Tuple data type is appropriate for
3 operations, such as insertion and
accessing the elements
deletion.

Tuple consumes less memory as


4 Lists consume more memory
compared to the list

Tuple does not have many built-in


5 Lists have several built-in methods
methods.

Unexpected changes and errors are Because tuples don’t change they are
6
more likely to occur far less error-prone.

Syntax: Enclosed in Square ([])


7 Syntax: Enclosed in Square (()) bracket
bracket
Example: Example:
8
Employee = [‘A’, ‘B’, ‘C’] Employee = (1001, 1002, 1003)

b) Write a python program takes in a number and find the sum of digits in a 4M
number.

Ans Number = int(input("Please Enter any Number: ")) 4 M for


correct
Sum = 0 program.
while(Number > 0):
Reminder = Number % 10
Sum = Sum + Reminder
Number = Number //10
print("\n Sum of the digits of Given Number = %d" %Sum)
Output:
Please Enter any Number: 12
Sum of the digits of Given Number = 3

c) Write a program function that accepts a string and calculate the number of 4M
uppercase letters and lower case letters.

Ans Str=input("Enter a String -: ") 4 M for


def upperlower(Str): correct
lower=0 program.
upper=0
for i in Str:
Page No: 9 | 19
Campusify - Free Study Material - https://t.me/campusifyy
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
if(i.islower()):
lower+=1
elif(i.isupper()):
upper+=1
print("The number of lowercase characters is:",lower)
print("The number of uppercase characters is:",upper)

upperlower(Str)

Output -
Enter a String -: Welcome to Python programing
The number of lowercase characters is: 23
The number of uppercase characters is: 2

or

string = input("Enter a String -: ")


def upperlower(string):
upper = 0
lower = 0
for i in range(len(string)):
# For lower letters
if (ord(string[i]) >= 97 and ord(string[i]) <= 122): #ord() function is used to convert
a single Unicode character into its integer representation
lower += 1
# For upper letters
elif (ord(string[i]) >= 65 and ord(string[i]) <= 90):
upper += 1

print('Lower case characters = %s' %lower, '\nUpper case characters = %s' %upper)

upperlower(string)

Output-
Enter a String -: Welcome to Python programming
Lower case characters = 24
Upper case characters = 2

d) Write a python program to create class student with roll-no. and display its 4M
contents.

Ans class Student: 4 M for


correct
def init (self, rollno): program.
self.rollno = rollno

Page No: 10 | 19
Campusify - Free Study Material - https://t.me/campusifyy
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________

def set_data(self, rollno):


self.rollno = rollno

def display_data(self):
print(f"Roll No: {self.rollno}")
student1 = Student(10)
student1.display_data()

Output:
Rollno = 10

e) Explain following functions with example: 4M

i) The open() function

ii) The write() function

Ans i) The open() function 2 M each


for one
The open() function opens a file and returns it as a file object. point and
Syntax: proper
explanation
open(file, mode) with
example.
file: The path and name of the file
mode: A string, define which mode you want to open the file in:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exist

In addition you can specify if the file should be handled as binary or text mode
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)

Page No: 11 | 19
Campusify - Free Study Material - https://t.me/campusifyy
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
Example:

Open a file and print the content:

f = open("demofile.txt", "r")
print(f.read())

ii) The write() function

The write() method writes a specified text to the file.

Where the specified text will be inserted depends on the file mode and stream position.

"a": The text will be inserted at the current file stream position, default at the end of the
file.

"w": The file will be emptied before the text will be inserted at the current file stream
position, default 0.

Syntax:
file.write(byte)
byte: The text or byte object that will be inserted.
Example:
Open the file with "a" for appending, then add some text to the file:
f = open("demofile2.txt", "a")
f.write("Hi!")
f.close()

#open and read the file after the appending:


f = open("demofile2.txt", "r")
print(f.read())

5. Attempt any TWO of the following: 12 M

a) Write the output for the following if the variable course = "Python" 6M

>>> course [ : 3 ]

>>> course [ 3 : ]

>>> course [ 2 : 2 ]

>>> course [:]

Page No: 12 | 19
Campusify - Free Study Material - https://t.me/campusifyy
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
>>> course [-1]

>>> course [1]

Ans >>>course[:3] 1 M for


each one
Ans: Pyt question

course[3:]

Ans: hon

>>>course[2:2]

Ans: a slice starting and ending at the same index, which results in an empty string. Slicing
in this way doesn't include any characters between the specified indices.

>>>course[:]

Ans: Python

>>>course[-1]

Ans: n

>>> course[1]

Ans: y

b) Write a python program to generate five random integers between 10 and 50 6M


using numpy library.

Ans import numpy as np 6 M- Any


correct logic
random_integer = np.random.randint(10, 51) program

print(f"Random integer between 10 and 50: {random_integer}")

# If you want to generate an array of random integers, you can specify the size

# For example, to generate 5 random integers between 10 and 50:

random_integers_array = np.random.randint(10, 51, size=5)

print(f"Array of random integers between 10 and 50: {random_integers_array}")

c) Write a Python program to create a class 'Diploma' having a method 6M


‘getdiploma’ that prints "I got a diploma". It has two subclasses namely 'CO'
and 'IF' each oſ having a method with the same name that prints "I am with

Page No: 13 | 19
Campusify - Free Study Material - https://t.me/campusifyy
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
CO diploma" and "I am with IF diploma' respectively. Call the method by
creating an object of each of the three classes.

Ans class Diploma: 6 M - Any


correct logic
def getdiploma(self): program

print("I got diploma")

class CO(Diploma):

def getdiploma(self):

print("I am with CO diploma")

class IF(Diploma):

def getdiploma(self):

print("I am with IF diploma")

# Create objects of each class

diploma_obj = Diploma()

co_obj = CO()

if_obj = IF()

# Call the getdiploma method on each object

diploma_obj.getdiploma() # Output: I got diploma

co_obj.getdiploma() # Output: I am with CO diploma

if_obj.getdiploma() # Output: I am with IF diploma

6. Attempt any TWO of the following: 12 M

a) Explain multiple inheritance and write a python program to implement it. 6M

Page No: 14 | 19
Campusify - Free Study Material - https://t.me/campusifyy
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
Ans Multiple inheritance is a feature in object-oriented programming where a class can 2 M-
inherit attributes and methods from more than one parent class. This allows a class to Explanation,
combine and reuse code from multiple classes, promoting code reuse and modular 4 M-any
suitable
design.
example
In Python, you can achieve multiple inheritance by specifying multiple parent classes in
the definition of a child class.

Program:

class Person:

def init (self, name, age):

self.name = name

self.age = age

def display_person(self):

print(f"Name: {self.name}, Age: {self.age}")

class Employee:

def init (self, employee_id, position):

self.employee_id = employee_id

self.position = position

def display_employee(self):

print(f"Employee ID: {self.employee_id}, Position: {self.position}")

class Manager(Person, Employee):

def init (self, name, age, employee_id, position, department):

Person. init (self, name, age)

Employee. init (self, employee_id, position)

Page No: 15 | 19
Campusify - Free Study Material - https://t.me/campusifyy
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
self.department = department

def display_manager(self):

self.display_person()

self.display_employee()

print(f"Department: {self.department}")

# Create an instance of Manager

manager = Manager("Alice", 35, "M123", "Project Manager", "IT")

# Display manager details

manager.display_manager()

b) Write a Python program to create user defined exception that will check 6M
whether the password is correct or not.

Ans class InvalidPasswordException(Exception): 6 M - Any


correct logic
"""Exception raised for invalid passwords.""" program

def init (self, message="Password is incorrect"):

self.message = message

super(). init (self.message)

def check_password(input_password):

correct_password = "SecurePassword123" # Replace with the actual correct password

if input_password != correct_password:

raise InvalidPasswordException("The password you entered is incorrect.")

else:

Page No: 16 | 19
Campusify - Free Study Material - https://t.me/campusifyy
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
print("Password is correct. Access granted.")

# Main program to check the password

try:

user_password = input("Enter your password: ")

check_password(user_password)

except InvalidPasswordException as e:

print(e)

c) Describe various modes of file object. Explain any three in detail. 6M

Ans 1. Read Mode ('r'): Any 3


modes, each
• This is the default mode. It opens the file for reading. mode for 2
• If the file doesn't exist, it raises a FileNotFoundError. M

• When opened in this mode, attempting to write to the file will raise a
UnsupportedOperation error.
• Example: open('file.txt', 'r')
2. Write Mode ('w'):
• Opens the file for writing. If the file doesn't exist, it creates a new file.
• If the file already exists, it truncates the file to zero length.
• Example: open('file.txt', 'w')
3. Append Mode ('a'):
• Opens the file for writing. If the file doesn't exist, it creates a new file.
• If the file already exists, it appends data to the end of the file.
• Example: open('file.txt', 'a')
4. Binary Mode ('b'):
• Opens the file in binary mode. It's used in conjunction with other modes
like read ('rb'), write ('wb'), or append ('ab') to deal with binary files like
images, executables, etc.
• Example: open('image.jpg', 'rb')
5. Text Mode ('t'):

Page No: 17 | 19
Campusify - Free Study Material - https://t.me/campusifyy
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
• This is the default mode for text files (although you don't explicitly specify
it). It's used to handle text files and performs encoding/decoding of text
automatically.
• Example: open('file.txt', 'rt')
6. Read and Write Mode ('r+'):
• Opens the file for both reading and writing.
• The file pointer is at the beginning of the file.
• Example: open('file.txt', 'r+')
7. Write and Read Mode ('w+'):
• Opens the file for both reading and writing.
• If the file doesn't exist, it creates a new file.
• If the file exists, it truncates the file to zero length.
• Example: open('file.txt', 'w+')
Detailed Explanation of Three Modes:

1. Read Mode ('r'):


• This mode is primarily used when you want to read data from an existing
file.
• It's useful for operations like reading configuration files, log files, or any
other file where you need to retrieve information.
• Reading from a file opened in read mode does not modify the file.
• Attempting to write to a file opened in read mode will raise an error.
2. Write Mode ('w'):
• This mode is used when you want to write data to a file.
• If the file already exists, opening it in write mode will truncate the file to
zero length, effectively deleting its contents.
• If the file doesn't exist, Python will create a new file.
• It's commonly used for tasks like writing output to a file, logging data, or
creating new files.
3. Append Mode ('a'):
• Append mode is similar to write mode but instead of truncating the file, it
appends data to the end of the file.
• If the file doesn't exist, it creates a new file.

Page No: 18 | 19
Campusify - Free Study Material - https://t.me/campusifyy
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
• It's useful when you want to add data to an existing file without overwriting
its contents.
• Common use cases include logging, adding new entries to a file, or
maintaining a history of operations.

Page No: 19 | 19
Campusify - Free Study Material - https://t.me/campusifyy

You might also like