0% found this document useful (0 votes)
2 views33 pages

Shubh Py

The document is a lab manual for the Programming in Python course at IPS Academy, detailing the vision and mission of the institute and department, program education objectives, outcomes, and specific course outcomes. It includes laboratory regulations, a list of experiments, and a brief introduction to Python programming and its data types. The manual serves as a guide for students in their practical learning and application of Python programming concepts.
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)
2 views33 pages

Shubh Py

The document is a lab manual for the Programming in Python course at IPS Academy, detailing the vision and mission of the institute and department, program education objectives, outcomes, and specific course outcomes. It includes laboratory regulations, a list of experiments, and a brief introduction to Python programming and its data types. The manual serves as a guide for students in their practical learning and application of Python programming concepts.
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/ 33

IPS ACADEMY

INDORE
INSTITUTE OF ENGINEERING & SCIENCE
COMPUTER SCIENCE & INFORMATION
TECHNOLOGY DEPARTMENT

LAB MANUAL
(2023-24)
(PCC CI02)Programming in PYTHON

Name…..shubh rathore

Year… 2nd Semester.. 3rd

Class rollno…..98

Enrollment no.. 0808CI231198

1
CONTENTS

⦁ Vision Mission of the Institute


⦁ Vision Mission of the Department
⦁ PEOs
⦁ POs
⦁ PSOs
⦁ COs
⦁ Content beyond Syllabus. ( if any)
⦁ Laboratory Regulations and Safety Rules
⦁ Index
⦁ Experiments

2
Vision of the Institute
To be the fountain head of novel ideas & innovations in science & technology &
persist to be a foundation of pride for all Indians.

Mission of the Institute

⦁ To provide value based broad Engineering, Technology and Science where


education in students is urged to develop their professional skills.

⦁ To inculcate dedication, hard work, sincerity, integrity and ethics in building


up overall professional personality of our student and faculty.

⦁ To inculcate a spirit of entrepreneurship and innovation in passing out students.

⦁ To instigate sponsored research and provide consultancy services in


technical, educational and industrial areas.

Program Education Objectives (PEOs)

PEO 1: To prepare students for successful careers in software industry


that meet the needs of Indian and multinational companies.
PEO 2: To provide students with solid foundation in mathematical, scientific
and engineering fundamentals to solve engineering problems and required also

3
to pursue higher studies.

PEO 3: To develop the ability to work with the core competence of


computer science & engineering i.e. software engineering, hardware
structure & networking concepts so that one can find feasible solution to
real world problems.
PEO 4: To inseminate in students effective communication skills, team work,
multidisciplinary approach, and an ability to relate engineering issues to
broader social context.

PEO 5: To motivate students perseverance for lifelong learning and to


introduce them to professional ethics and codes of professional practice.

Program Outcomes (POs)

PO1. Engineering knowledge: Apply the knowledge of mathematics, science,


engineering fundamentals, and an engineering specialization to the solution of
complex engineering problems.

PO2. Problem analysis: Identify, formulate, research literature, and analyze


complex engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences, and engineering sciences.

PO3.Design/development of solutions: Design solutions for complex engineering


problems and design system components or processes that meet the specified needs
with appropriate consideration for the public health and safety, and the cultural,

4
societal, and environmental considerations.

PO4. Conduct investigations of complex problems: Use research-based


knowledge and research methods including design of experiments, analysis and
interpretation of data, and synthesis of the information to provide valid
conclusions.

PO5. Modern tool usage: Create, select, and apply appropriate techniques,
resources, and modern engineering and IT tools including prediction and modeling
to complex engineering activities with an understanding of the limitations.

PO6. The engineer and society: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the professional engineering practice.

PO7. Environment and sustainability: Understand the impact of the professional


engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.

PO8. Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.

PO9. Individual and team work: Function effectively as an individual, and as a


member or leader in diverse teams, and in multidisciplinary settings.
PO10. Communication: Communicate effectively on complex engineering
activities with the engineering community and with society at large, such as, being
able to comprehend and write effective reports and design documentation, make
effective presentations, and give and receive clear instructions.
PO11. Project management and finance: Demonstrate knowledge and
understanding of the engineering and management principles and apply these to
one’s own work, as a member and leader in a team, to manage projects and in
multidisciplinary environm

PO12. Life-long learning: Recognize the need for, and have the preparation and
ability to engage in independent and life-long learning in the broadest context of
technological change

Program Specific Outcomes (PSOs)

⦁ Apply Concepts in core areas of computer science -Data Structures,


Database Management System, Operating System, Computer
Networks and Software Engineering to solve technical issues.

5
⦁ Apply Software Engineering principal and practices to provide software
solutions.

⦁ Ability to work in team and apply the knowledge acquired to develop


new real life system and able to adapt societal need of future.

Course Outcome of Programming Practices (PCC-CI02(P))


CO1: Install Python and have knowledge of syntax of Python. BT1
CO2: Describe the numbers, Math functions, Strings, List, Tuples and Dictionaries in
Python. BT2, BT3 CO3: Express different Decision making statements and
Functions. BT3
CO4: Develop code in Python using functions, loops, etc. BT4
CO5: Design GUI Applications in Python and evaluate different database operations.
BT3

Laboratory Regulations and Safety Rules

⦁ Without Prior permission do not enter into the Laboratory.


⦁ While entering into the LAB students should wear their ID cards.
⦁ The Students should come with proper uniform.
⦁ Student should not use mobile phone inside the laboratory.
⦁ Students should sign in the LOGIN REGISTER before entering into the
laboratory.
⦁ Students should come with observation and record note book to the laboratory.
⦁ Do not change any computer setting.
⦁ Students should maintain silence inside the laboratory.
⦁ After completing the laboratory exercise, make sure to SHUTDOWN the
system properly.

6
INDEX

S.
Experiment Name Date Grade Signature
No.
1. Introduction to python programming and python
datatypes. (CO1)
2. Python program to find the union of two lists.(CO1)
3 Python program to find the intersection of two
lists.(CO1)
4 Python program to remove the“N”the occurrence
of the given word in a list where words repeat.
(CO2)
5 Python program to count the occurrences of each word
in a given string sentence. . (CO2)
6 Pythonprogramtocheckifasubstringispresentina
given string. (CO2)
7 Python program to map two lists into a
dictionary. .(CO3
8 Python program to count the frequency of words
appearing in a string using a dictionary. (CO3)

7
9 Python program to create a dictionary with key as
first
characterandvalueaswordsstartingWiththatcharacter.
.(CO3)
10 Python program to find the length of a list using
recursion.
.(CO4)
11 Python program to read a file and capitalize the first
letter of every word in the file. .(CO5)
12 Python program to read the contents of a file in reverse
order. (CO5)

Experiment 1

AIM - Introduction to python programming and python


datatypes(CO1)

⦁ Introduction to Python Programming

Programming Python is a powerful, versatile, and beginner-friendly


programming language that's widely used in many fields, including
web development, data analysis, artificial intelligence, scientific
computing, and more. Here's a quick introduction to Python and its
data types

Python's syntax is designed to be readable and straightforward,


making it an excellent choice for beginners. Some key features of
Python include:

⦁ Simple and Easy to Learn: The syntax is clean and the language is
easy to understand.
⦁ Interpreted Language: Python code is executed line
by line, which makes debugging easier.
8
⦁ High-Level Language: You don't need to manage memory and other
low-level details.
⦁ Portable: Python code can run on different platforms without
modification.
⦁ Extensive Libraries: Python has a rich set of libraries and
frameworks that can simplify many tasks.

Python also supports multiple programming paradigms, including


procedural, object- oriented, and functional programming. This
flexibility allows developers to choose the best approach for a
particular problem. Procedural programming involves writing
procedures or functions that perform operations on data. In contrast,
object-oriented programming (OOP) organizes code into objects,
encapsulating data and functions that operate on the data. OOP
promotes code reusability and modularity. Additionally, functional
programming in Python allows for writing cleaner and more concise
code using pure functions, higher-order functions, and immutable
data.

Python comes with a comprehensive standard library, which provides


a wide array of modules and functions for common tasks such as file
I/O, networking, and data manipulation. Additionally, the Python
Package Index (PyPI) hosts thousands of third- party libraries and
frameworks, allowing developers to extend the language's
capabilities and build complex applications.

Exception handling is another important aspect of Python, enabling


developers to write robust and error-resistant code. Using try, except,
and finally blocks, programmers can gracefully handle runtime errors and
ensure that necessary cleanup actions are performed.

Python also supports various data types and data structures, including
numbers, strings, lists, tuples, sets, and dictionaries. These built-in
types provide the foundation for data manipulation and storage,
allowing developers to efficiently manage and process information.

⦁ Introduction to python datatypes

Certainly! Python data types are fundamental to managing and


9
manipulating data in Python programming. They define the kind of
data that can be stored and the operations that can be performed on
them. Python is known for its dynamic typing system, where
variables do not need to be explicitly declared with a type, and types
are determined at runtime based on the value assigned. Let's delve
into the various data types available in Python:

⦁ Numbers:
⦁ Integers (int): These are whole numbers without a decimal
point, such as 5, -42, or 1024. Python supports arbitrary-
precision integers, allowing you to work with very large
numbers.
⦁ Floating-point numbers (float): These are numbers with a
decimal point, such as 3.14, -0.001, or 2.71828. Floats
are used to represent real numbers and support scientific
notation.
⦁ Complex numbers (complex): These numbers have a
real part and an imaginary part, represented as a +
bj, where a is the real part and b is the imaginary
part. For example, 3 + 4j is a complex number.
⦁ Strings (str): Strings are sequences of characters, used to
represent text. They are enclosed in single quotes (' ') or
double quotes (" "). For example, 'hello' and "world" are
both strings. Python supports various string operations, such
as concatenation, slicing, and formatting.
⦁ Lists: Lists are ordered, mutable sequences of elements, defined by
square brackets ([
]). They can contain elements of different data types,
including other lists. For example, [1, 2, 3] and ['apple',
'banana', 'cherry'] are lists. Lists support various
operations like indexing, slicing, appending, and
removing elements.
⦁ Tuples: Tuples are ordered, immutable sequences of elements,
defined by parentheses (( )). Like lists, they can contain elements
of different data types. For example, (1, 2, 3) and ('a', 'b', 'c') are
tuples. Since tuples are immutable, their elements cannot be
changed after creation.

10
⦁ Sets: Sets are unordered collections of unique elements, defined by
curly braces ({
}). For example, {1, 2, 3} and {'a', 'b', 'c'} are sets. Sets support
operations like union, intersection, and difference, making them
useful for tasks involving unique elements and membership
testing.
⦁ Dictionaries (dict): Dictionaries are unordered collections of key-
value pairs, defined by curly braces ({ }). Each key must be
unique and immutable (e.g., strings, numbers, or tuples), while
values can be of any data type. For example, {'name': 'Alice',
'age': 30} is a dictionary. Dictionaries support operations like
adding, updating, and removing key-value pairs, and provide
efficient lookups based on keys.

In addition to these built-in data types, Python also supports other


specialized data structures and types, such as byte sequences, memory
views, and more, which are used for specific purposes and
performance optimizations.

Program to initialize
Python Datatypes :- Code :

my_int = 10
my_float = 10.5
my_string = "Hello, Python!"
my_list = [1, 2, 3, 4, 5]
my_tuple = (1, 2, 3)
my_dict = {"name": "shubh", "age": 25}
my_set = {1, 2, 3, 4, 5}
my_bool = True
my_none = None

11
print(f"Integer: {my_int}")
print(f"Float: {my_float}")
print(f"String: {my_string}")
print(f"List: {my_list}")
print(f"Tuple: {my_tuple}")
print(f"Dictionary: {my_dict}")
print(f"Set: {my_set}")
print(f"Boolean: {my_bool}")
print(f"NoneType: {my_none}")

OUTPUT

Viva Questions :-
⦁ What is a variable in Python?

Ans -A variable in Python is a symbolic name that references a value


stored in memory. It acts as a container for storing data that can be
manipulated and retrieved throughout a program. Variables are
created by assigning a value to a name using the assignment operator
=.
⦁ What is types of Operator?

Ans - Operators in Python are special symbols that perform operations


on variables and values. There are several types of operators:

12
⦁ Arithmetic Operators: Perform basic mathematical
operations like addition (+), subtraction (-),
multiplication (*), division (/), and more.
⦁ Comparison Operators: Compare values and return a
boolean result, such as equal to (==), not equal to (!=),
greater than (>), and less than (<).
⦁ Logical Operators: Combine boolean expressions and
return a boolean result, like and, or, and not.
⦁ Assignment Operators: Assign values to variables,
such as equals (=), plus equals (+=), and minus equals
(-=).
⦁ Bitwise Operators: Perform bit-level operations, like
AND (&), OR (|), XOR (^), and NOT (~).
⦁ Membership Operators: Test for membership in a sequence, like in
and not in.
⦁ Identity Operators: Compare the memory locations of two objects,
like is and is not.

Experiment 2
Aim: Python program to find union of two lists
13
Code:

list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]

union_list = list(set(list1) | set(list2))

print(f"Union of the two lists: {union_list}")

OUTPUT

VIVA QUESTIONS
⦁ What is list
Ans- A list in Python is an ordered and mutable collection of
elements. It can hold items of different data types (e.g., integers,
strings, etc.). Lists are created using square brackets [], and items are
indexed starting from 0. Lists allow modification, such as adding,
removing, or changing elements. Since they are mutable, you can
change their contents after creation.

⦁ What is List Items?

Ans- A list item in Python refers to an individual element or value


14
stored within a list. Each item in a list can be of any data type, such as
integers, strings, floats, or even other lists. List items are ordered and
are indexed, starting from 0 for the first item.

Key Points:

⦁ Order: The order of items is maintained.


⦁ Indexing: Items can be accessed using their index.
⦁ Mutable: List items can be modified.

Experiment – 3
Aim: Python program to find intersection of two lists.
Code:
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]

intersection_list = list(set(list1) & set(list2))

print(f"Intersection of the two lists: {intersection_list}")

OUTPUT

15
VIVA QUESTIONS:

⦁ What is intersection of two lists?

Ans- The intersection of two lists refers to the set of elements that
are common to both lists. In other words, it consists of the items that
appear in both lists, without duplication.

In Python, the intersection of two lists can be found by converting the


lists into sets and then using the set intersection operation. The result
is a collection of elements that exist in both lists.

⦁ What is a list() constructor?

Ans- The list() constructor in Python is a built-in function used to


create a list from an iterable (such as a string, tuple, set, or another
list). It can also be used to create an empty list if no argument is
provided.

Key Points:

⦁ Creates a list: Converts an iterable (like a string, tuple, or set) into


a list.
⦁ Empty list: Calling list() without any argument creates an empty
list.
⦁ Conversion: Useful for converting other data types (such as
tuples or strings) into a list format.

16
Experiment – 4

AIM - Python program to remove the“N”th occurrence of


the given word in a list where words repeat. (CO2)

Code :

def remove_nth_occurrence(lst, word, n):


count = 0
for i in range(len(lst)):
if lst[i] == word:
count += 1
if count == n:
del lst[i]
return lst
return lst

words = ["apple", "banana", "apple", "orange", "apple"]


result = remove_nth_occurrence(words, "apple", 2)
print(result)

OUTPUT

17
VIVA QUESTIONS:

⦁ What is range of indexes?

Ans- In Python, the range of indexes refers to the valid positions


(indices) you can use to access elements in an ordered collection like a
list, string, or tuple.

Key Points:

⦁ Start from 0: In Python, indexing starts at 0. The first item in a


collection has index 0, the second item has index 1, and so on.
⦁ Negative Indexes: Python also supports negative indexing,
where -1 refers to the last item, -2 refers to the second-to-last
item, and so on.
⦁ Length of Collection: The valid range of indexes for a
collection is from 0 to len(collection) - 1 for positive indices.
For negative indices, the range is from -1 (last item) to -
len(collection).

⦁ What is Python Collections (Arrays)?

Ans- In Python, collections refer to various data structures that are


used to store and manage multiple items. One of the most commonly
used collections is the array, though Python does not have a specific
array data type like other languages. Instead, Python provides several
collection types to handle ordered, unordered, and key-value based
data.

Key Types of Collections in Python:

⦁ List:
⦁ A list is an ordered, mutable collection that can hold
18
items of different data types.
⦁ Lists are created using square brackets [].
⦁ Lists allow duplicates and support various operations
like adding, removing, and modifying elements.

EXPERIMENT: 5

Aim: Python program to count the occurrences of each


word in a given string sentence. . (CO2)

CODE:

sentence = "hello class hello python class python"


words = sentence.split()

word_count = {}

for word in words:


if word in word_count:
word_count[word] += 1
else:

19
word_count[word] = 1
print(word_count)

OUTPUT

VIVA QUESTIONS:

⦁ What is String?

Ans- A string in Python is a sequence of characters enclosed within


either single quotes (') or double quotes ("). Strings are used to
represent text-based data, such as words, sentences, or any other
sequence of characters.

Key Features of a String:

⦁ Immutable: Strings in Python are immutable, meaning once a


string is created, its contents cannot be changed.
⦁ Ordered: The characters in a string have a defined order, and
each character can be accessed by its index.
⦁ Can contain different characters: A string
can contain letters,
numbers, punctuation marks, and special characters.
⦁ Supports indexing and slicing: You can access individual
characters in a string using an index, and you can slice a
string to get substrings.

⦁ How to find occurrences of a each word in a string in


20
Python?
Ans- To find the occurrences of each word in a string in Python, you
can follow these basic steps:

⦁ Split the string into words: You first need to split the string
into individual words. This can be done using the split() method,
which separates the string by spaces or any other delimiters.
⦁ Normalize the words: To ensure the comparison is case-
insensitive, you can convert the entire string to lowercase using
the lower() method. This ensures that words like "Hello" and
"hello" are treated the same.
⦁ Count the occurrences: After splitting the string into words,
you can count the occurrences of each word using a dictionary
or Python's collections.Counter class. A dictionary would map
each word to its frequency, while Counter automatically counts
the frequency of elements.

EXPERIMENT-06

Aim: Python program to check if a substring is present in a


given string. (CO2)

Code:

string = "Hello, welcome to the world of Python"


substring = "shubh"
21
if substring in string:
print("Substring is present")
else:
print("Substring is not present")

OUTPUT

Viva Questions :
What is a substring ?
Ans - A substring is a sequence of characters that appears
consecutively within another string. In simpler terms, a substring is a
portion or a segment of a longer string. For example, if we have the
string "hello world," the substrings could be "hello," "world," "lo wo,"
or even a single character like "h" or "o."

2.Explain the use of the in keyword in Python.


Ans - The in keyword is used to check if a value is present in a
sequence (such as a string, list, tuple, etc.). It returns True if the value
is found and False otherwise

22
EXPERIMENT-07

Aim: Python program to map two lists into a


dictionary. .(CO3)

Code:

keys = ["v", "w", "x"]


values = [4, 5, 6]

dictionary = dict(zip(keys, values))

print(dictionary)
OUTPUT

Viva Questions :
⦁ what is dictionary in python ?

Ans – A dictionary in Python is a collection data type that stores


23
key-value pairs. Each key
must be unique and immutable (e.g., strings, numbers, tuples), while
values can be of any
data type. Dictionaries are defined using curly braces {}, with keys
and values separated by

a colon :

⦁ What are some real-world applications of mapping lists to


dictionaries?

Ans - Mapping lists to dictionaries is useful for creating lookup tables,


processing CSV

and JSON data, text processing, storing configuration settings,


caching results, representing

graph adjacency lists, and managing user session data in web


applications. It improves data
organization, retrievale

EXPERIMENT-08
Aim: Python program to count the frequency of words
appearing in a string using a dictionary. (CO3)
Code:
string = "apple banana apple orange banana apple grapes"
words = string.split()

24
frequency = {}

for word in words:


if word in frequency:
frequency[word] += 1
else:
frequency[word] = 1

print(frequency)

OUTPUT

Viva Questions :

⦁ Mention some common string methods.

Ans – 1. str.lower(): Converts all characters in the string to lowercase.


⦁ str.upper(): Converts all characters in the string to uppercase.

⦁ str.strip(): Removes leading and trailing whitespace from the string.

⦁ str.replace(old, new): Replaces all occurrences of a substring with


another substring.
25
2. Explain the use of the split() method in this program.

Ans - The split() method in Python is used to split a string into a list
of substrings based on a specified delimiter (separator). In the
provided program, the split() method is called on the input string to
break it down into individual words, which are then stored in a list.

EXPERIMENT-09

Aim: Python program to create a dictionary with key as


first character and value as words starting With that
character.(CO3)

Code:

string = "apple banana apple cherry orange banana apple"


words = string.split()
dictionary = {}

for word in words:


key = word[0]

if key in dictionary:
dictionary[key].append(word)
else:
dictionary[key] = [word]

print(dictionary)

output :

26
Viva Questions :

⦁ What does a key and value represent in dictionary ?


Ans - In a Python dictionary, a key and value represent a unique
pair where the key is used to access the value. Here's a breakdown:
Key: A unique identifier that is immutable (e.g., strings,
numbers, tuples). Each key in a dictionary must be distinct.
Value: The data associated with the key. Values can be of any data
type, such as strings, numbers, lists, or even other dictionaries.

⦁ Mention some common dictionary methods .


Ans – 1. dict.get(key, default=None): Returns the value for the
specified key if it exists, otherwise returns the default value.
⦁ dict.keys(): Returns a view object that displays a list of all the keys in
the dictionary.

⦁ dict.values(): Returns a view object that displays a list of all the


values in the dictionary.
⦁ dict.items(): Returns a view object that displays a list of
dictionary's key-value tuple pairs.

27
EXPERIMENT-10

Aim: Python program to find the length of alistusing


recursion. .(CO4)
Code:

def list_length(lst):
if not lst:
return 0
return 1 + list_length(lst[1:])

my_list = [1, 8, 9, 7, 5]
print(my_list)
28
print(list_length(my_list))

OUTPUT

Viva Questions :
⦁ what do you mean by recursion ?

Ans - Recursion is a programming concept where a function calls


itself in order to solve a problem. The function typically solves a
smaller instance of the same problem, and the process repeats until it
reaches a base case, which is a condition that stops the recursion.
Recursion is often used for problems that can be broken down into
smaller, similar subproblems, such as calculating the factorial of a
number, traversing a tree, or solving the Fibonacci sequence.

⦁ what are the other methods to calculate length of


list ?
Ans - Apart from using the len() function, you can calculate the length
of a list using methods like iterating through the list with a loop, using
list comprehension, utilizing the
reduce() function, or applying recursion. These methods involve
counting each element in the list to determine its total length.

29
EXPERIMENT-11

Aim: Python program to read a file and capitalize the first


letter of every word in the file. .(CO5)
Code:

with
open("sample.txt",
"r") as file: content
= file.read()
capitalized_content = " ".join(word.capitalize() for
word in content.split()) print(capitalized_content)

OUTPUT

(Assume sample.txt contains: my name is shubh. i am a


student of csit)

Viva Questions :

⦁ What happens if the specified file does not exist?

30
Ans - If the specified file does not exist, a FileNotFoundError is raised.
In the provided program, this error is caught by the try...except block,
and the program prints an error
message indicating that the file does not exist. This ensures that the
program handles such exceptions gracefully and informs the user about
the issue.

⦁ Explain the difference between read() and


write() methods. Ans - The read() method reads the
entire content of a file as a string, while the write() method
writes a string to a file. read() is used to retrieve data from
a file, whereas write() is used to store data in a file.

EXPERIMENT-12
Aim: Python program to read the contents of a file in
reverse order. (CO5)
Code:

with

open("sample.txt

", "r") as file: lines

31
= file.readlines()

for line in

reverse

d(lines):

print(lin

e.strip())

OUTPUT

Assume sample.txt contains:

hello

python

class

Viva Questions :

⦁ Why is the try...except block used ?

Ans - The try...except block is used to handle potential errors that


32
may occur during the execution of the program, such as file not found
errors. It ensures that the program can handle exceptions gracefully
and provides appropriate error messages instead of crashing.

⦁ What is the advantage of using the with statement


to open files? Ans - The `with` statement in Python is used to
open files because it ensures proper resource management. It
automatically handles opening and closing the file, even if an
exception occurs during file operations. This helps prevent resource
leaks and ensures that the file is properly closed, reducing the risk of
data corruption or other file-related issues.

33

You might also like