0% found this document useful (0 votes)
3 views16 pages

PSP - Cia 2

The document provides a comprehensive overview of problem-solving techniques using Python, covering string manipulation, list operations, and file handling. It includes explanations of methods such as slicing, splitting strings, and using list methods like append, extend, and remove, along with examples and outputs. Additionally, it discusses the differences between tuples and lists, file modes, and methods for reading data from files.

Uploaded by

arivu240520
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)
3 views16 pages

PSP - Cia 2

The document provides a comprehensive overview of problem-solving techniques using Python, covering string manipulation, list operations, and file handling. It includes explanations of methods such as slicing, splitting strings, and using list methods like append, extend, and remove, along with examples and outputs. Additionally, it discusses the differences between tuples and lists, file modes, and methods for reading data from files.

Uploaded by

arivu240520
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/ 16

Problem Solving using Python

CIA – 2 / Review Questions

Part – A
1. What is purpose of Slicing, and write the output of the following code?
s = "Python"
print(s[1:4])
Slicing is used to extract a portion (substring) of a string by specifying a start, stop, and step index.
It allows accessing specific segments of a string without modifying the original string.
Syntax:
string[start : stop : step]
start (inclusive) → Beginning index (default: 0).
stop (exclusive) → End index (default: len(string)).
step → Interval between characters (default: 1).

The output of the given code is "yth".

2. What does the split() method do in Python strings with an example?


It splits a string into a list of substrings based on a specified delimiter (default: whitespace).
Example:
S = "I love coding in python"
print(S.split())
Output:
['I', 'love', 'coding', 'in', 'python']

3. Write a Python statement to check if the word "code" and "love" exists in the string s = "I love coding
in python".
S = "I love coding in python"
print("Existence of the word, code =", "code" in S)
print("Existence of the word, love =", "love" in S)
Output:
Existence of the word, code = False
Existence of the word, love = True

4. How do you remove leading and trailing whitespace from a String? Also, write a code for the same
including Concatenation.
The strip() method is used to remove leading and trailing whitespace (spaces, tabs, newlines \n) for
specified characters from a string.
Example:
S1 = " I love coding "
S2 = "in Python"
print("With Space:", S1 + " " + S2)
print("Removing Space:", S1.strip()+ " " + S2)
Output:
With Space: I love coding in Python
Removing Space: I love coding in Python

Page 1 of 16
5. How do you add an element 50 at the end of a list [10, 20, 30] and add it with the list [65, 75, 85]?
L1 = [10, 20, 30]
L2 = [65, 75, 85]
print("list L1 = ", L1)
print("list L2 = ", L2)
L1.append(50)
print("now the list L1 = ", L1)
L3 = L1 + L2
print("Adding two List = ", L3)
Output:
list L1 = [10, 20, 30]
list L2 = [65, 75, 85]
now the list L1 = [10, 20, 30, 50]
Adding two List = [10, 20, 30, 50, 65, 75, 85]

6. How do you remove an element 75 from the list [65, 75, 85] and add it with the list [10, 20, 30]?
L1 = [65, 75, 85]
L2 = [10, 20, 30]
print("list L1 = ", L1)
print("list L2 = ", L2)
L1.remove(75)
print("now the list L1 = ", L1)
L3 = L1 + L2
print("Adding two List = ", L3)
Output:
list L1 = [65, 75, 85]
list L2 = [10, 20, 30]
now the list L1 = [65, 85]
Adding two List = [65, 85, 10, 20, 30]

7. Justify, whether you can modify a tuple after creation? Write the difference between a tuple and a
list in Python?
No, tuples are immutable, meaning their elements cannot be changed after creation.
Tuple vs. List:
Tuple:
Immutable (cannot be modified), uses ().
Fixed data (e.g., coordinates, database records).
Tuples only have count() and index().
Example:
my_tuple = (1, 2, 3, 4, 5)
List:
Mutable (can be modified), uses [].
Dynamic data (e.g., appending, removing).
Lists have append(), remove(), sort(), etc.
Example:
my_list = [1, 2, 3, 4, 5]

Page 2 of 16
8. How do you convert a list [1, 2, 3] into a tuple and vice versa?
List into Tuple:
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple)
print(type(my_tuple))
Output:
(1, 2, 3)
<class 'tuple'>

Tuple into List:


my_tuple = (1, 2, 3)
my_list = list(my_tuple)
print(my_list)
print(type(my_list))
Output:
[1, 2, 3]
<class 'list'>

9. List out any four File modes and brief them.


Mode Description
'r' Read mode (default) – Opens a file for reading. Raises an error if the file does not exist.
'w' Write mode – Opens a file for writing. Creates a new file if it doesn’t exist, overwrites
existing content.
'a' Append mode – Opens a file for writing but appends new data at the end (does not
overwrite). Creates a file if it doesn’t exist.
'x' Exclusive creation – Opens a file for writing only if it doesn’t exist, otherwise raises an error.
'b' Binary mode – Opens a file in binary mode (e.g., 'rb', 'wb'). Used for non-text files
(images, videos, etc.).
't' Text mode (default) – Opens a file in text mode (e.g., 'rt', 'wt').
'+' Read and Write mode – Opens a file for both reading and writing (e.g., 'r+', 'w+', 'a+').

Combined Modes
Mode Description
'r+' Read + Write – Opens a file for both reading and writing. File pointer at the beginning.
'w+' Write + Read – Opens a file for both writing and reading. Overwrites existing content.
'a+' Append + Read – Opens a file for both appending and reading. File pointer at the end.
'rb' Read Binary – Reads a file in binary mode.
'wb' Write Binary – Writes to a file in binary mode.

10. What are the methods used to read data from files?
(1) read()
Reads the entire content of the file as a single string (or bytes in binary mode).
Syntax:
content = file.read(size)
where, size (optional): Maximum characters/bytes to read. If omitted, reads the whole file.
(2) readline()
Reads one line at a time (including the newline \n).

Page 3 of 16
Syntax:
line = file.readline(size)
where, size (optional): Limits characters read from the line.
(3) readlines()
Reads all lines into a list of strings, where each element is a line.
Syntax:
lines = file.readlines(hint)
where, hint (optional): Approximate bytes to read before stopping.

Part – B
1. Given list1 = [1, 2, 3] and list2 = [4, 5, 6], perform the following operations:
 Concatenate them.
 Repeat list1 three times.
 Find the index of 5 in list2.
 Check if 3 exists in list1.
 Slice list2 to get [5, 6].

# Given lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]

# Concatenate them
concatenated = list1 + list2
print("Concatenated list:", concatenated) # Output: [1, 2, 3, 4, 5, 6]

# Repeat list1 three times


repeated = list1 * 3
print("Repeated list1 three times:", repeated) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]

# Find the index of 5 in list2


index_of_5 = list2.index(5)
print("Index of 5 in list2:", index_of_5) # Output: 1

# Check if 3 exists in list1


exists_3 = 3 in list1
print("Does 3 exist in list1?", exists_3) # Output: True

# Slice list2 to get [5, 6]


sliced_list2 = list2[1:]
print("Sliced list2 [5, 6]:", sliced_list2) # Output: [5, 6]

Output:
Concatenated list: [1, 2, 3, 4, 5, 6]
Repeated list1 three times: [1, 2, 3, 1, 2, 3, 1, 2, 3]
Index of 5 in list2: 1
Does 3 exist in list1? True
Sliced list2 [5, 6]: [5, 6]

Page 4 of 16
2. Given list1 = [100, 200, 300] and list2 = [700, 800, 900], perform the following operations:
• Concatenate them.
• Repeat list2 three times.
• Find the index of 300 in list2.
• Check if 200 exists in list1.
• Slice list2 to get [800, 900].

# Given lists
list1 = [100, 200, 300]
list2 = [700, 800, 900]

# Concatenate them
concatenated = list1 + list2
print("Concatenated list:", concatenated) # Output: [100, 200, 300, 700, 800, 900]

# Repeat list2 three times


repeated = list2 * 3
print("Repeated list2 three times:", repeated) # Output: [700, 800, 900, 700, 800, 900, 700, 800, 900]

# Find the index of 300 in list1 (not list2, since 300 isn't in list2)
index_of_300 = list1.index(300)
print("Index of 300 in list1:", index_of_300) # Output: 2

# Check if 200 exists in list1


exists_200 = 200 in list1
print("Does 200 exist in list1?", exists_200) # Output: True

# Slice list2 to get [800, 900]


sliced_list2 = list2[1:]
print("Sliced list2 [800, 900]:", sliced_list2) # Output: [800, 900]

Output:
Concatenated list: [100, 200, 300, 700, 800, 900]
Repeated list2 three times: [700, 800, 900, 700, 800, 900, 700, 800, 900]
Index of 300 in list1: 2
Does 200 exist in list1? True
Sliced list2 [800, 900]: [800, 900]

3. Demonstrate the use of List Methods for the list [1, 2, 3].

# Initialize the list


my_list = [1, 2, 3]
print("Original list:", my_list)

# 1. append() - Adds an element at the end of the list


my_list.append(4)
print("After append(4):", my_list) # [1, 2, 3, 4]

# 2. extend() - Adds all elements of an iterable to the end


my_list.extend([5, 6])
Page 5 of 16
print("After extend([5, 6]):", my_list) # [1, 2, 3, 4, 5, 6]

# 3. insert() - Inserts an element at a specific position


my_list.insert(0, 0) # Insert 0 at index 0
print("After insert(0, 0):", my_list) # [0, 1, 2, 3, 4, 5, 6]

# 4. remove() - Removes the first occurrence of a value


my_list.remove(3) # Removes the first 3 found
print("After remove(3):", my_list) # [0, 1, 2, 4, 5, 6]

# 5. pop() - Removes and returns an element at given index


popped = my_list.pop(1) # Removes element at index 1 (value 1)
print("After pop(1):", my_list) # [0, 2, 4, 5, 6]
print("Popped element:", popped) # 1

# 6. clear() - Removes all elements from the list


my_list.clear()
print("After clear():", my_list) # []

Output:
Original list: [1, 2, 3]
After append(4): [1, 2, 3, 4]
After extend([5, 6]): [1, 2, 3, 4, 5, 6]
After insert(0, 0): [0, 1, 2, 3, 4, 5, 6]
After remove(3): [0, 1, 2, 4, 5, 6]
After pop(1): [0, 2, 4, 5, 6]
Popped element: 1
After clear(): []

4. Demonstrate the use of List Methods for the list [350, 250, 150].

# Initialize the list


my_list = [350, 250, 150]
print("Original list:", my_list)

# append() - Adds an element to the end of the list


my_list.append(50)
print("After append(50):", my_list) # [350, 250, 150, 50]

# extend() - Adds multiple elements to the end


my_list.extend([450, 550])
print("After extend([450, 550]):", my_list) # [350, 250, 150, 50, 450, 550]

# insert() - Inserts an element at a specific position


my_list.insert(2, 200) # Insert 200 at index 2
print("After insert(2, 200):", my_list) # [350, 250, 200, 150, 50, 450, 550]

# remove() - Removes the first occurrence of a value


my_list.remove(250) # Removes the first 250 found
print("After remove(250):", my_list) # [350, 200, 150, 50, 450, 550]

Page 6 of 16
# pop() - Removes and returns an element at given index
popped = my_list.pop(3) # Removes element at index 3 (value 50)
print("After pop(3):", my_list) # [350, 200, 150, 450, 550]
print("Popped element:", popped) # 50

# clear() - Removes all elements from the list


my_list.clear()
print("After clear():", my_list) # []

Output:
Original list: [350, 250, 150]
After append(50): [350, 250, 150, 50]
After extend([450, 550]): [350, 250, 150, 50, 450, 550]
After insert(2, 200): [350, 250, 200, 150, 50, 450, 550]
After remove(250): [350, 200, 150, 50, 450, 550]
After pop(3): [350, 200, 150, 450, 550]
Popped element: 50
After clear(): []

---------------------

5. Write a python program for the tuple ((10, 20), (30, 40), (50, 60, 70), (80, 90)). Access the value 50,
Count the tuple and extract (30, 40) using slicing.

# Given nested tuple


nested_tuple = ((10, 20), (30, 40), (50, 60, 70), (80, 90))

# Access the value 50


value_50 = nested_tuple[2][0]
print("Accessed value 50:", value_50)

# Count the number of elements in the tuple


tuple_count = len(nested_tuple)
print("Number of elements in tuple:", tuple_count)

# Extract (30, 40) using slicing


extracted_slice = nested_tuple[1]
print("Extracted slice (30, 40):", extracted_slice)

Output:
Accessed value 50: 50
Number of elements in tuple: 4
Extracted slice (30, 40): (30, 40)

6. Write a python program for the tuple ((25, 15), (45, 35), (75, 65, 55), (95, 85)). Access the value 55,
Count the tuple and extract (75, 65) using slicing.

# Given nested tuple


nested_tuple = ((25, 15), (45, 35), (75, 65, 55), (95, 85))

Page 7 of 16
# 1. Access the value 55
value_55 = nested_tuple[2][2]
print("Accessed value 55:", value_55)

# 2. Count the number of elements in the tuple


tuple_count = len(nested_tuple)
print("Number of elements in tuple:", tuple_count)

# 3. Extract (75, 65) using slicing


extracted_slice = nested_tuple[2][0:2]
print("Extracted slice (75, 65):", extracted_slice)

Output:
Accessed value 55: 55
Number of elements in tuple: 4
Extracted slice (75, 65): (75, 65)

7. Write the python code to execute as follows


('M.S.Dhoni', 'Batsman & Wicket Keeper', 45)
('J.Srinath', 'Bowler', 20)
('S.Ganguly', 'Batsman', 85)

players = ("M.S.Dhoni", "J.Srinath", "S.Ganguly")


games = ("Batsman & Wicket Keeper", "Bowler", "Batsman")
scores = (45, 20, 85)

# Zip the tuples together


match = list(zip(players, games, scores))

# Print each tuple on a separate line


for player_info in match:
print(player_info)

Output:
('M.S.Dhoni', 'Batsman & Wicket Keeper', 45)
('J.Srinath', 'Bowler', 20)
('S.Ganguly', 'Batsman', 85)

8. Write the python code to exhibit the result as follows


('I.M.Vijayan', 'Foot Ball', 55)
('M.Bhupathi', 'Tennis', 50)
('P.V.Sindhu', 'Badminton', 29)

players = ("I.M.Vijayan", "M.Bhupathi", "P.V.Sindhu")


games = ("Foot Ball", "Tennis", "Badminton")
ages = (55, 50, 29)

# Zip the tuples together


match = list(zip(players, games, ages))
# Print each tuple on a separate line
for player_info in match:
Page 8 of 16
print(player_info)

Output:
('I.M.Vijayan', 'Foot Ball', 55)
('M.Bhupathi', 'Tennis', 50)
('P.V.Sindhu', 'Badminton', 29)

---------------------------------

9. Given students = {'Alice': {'age': 21, 'grade': 'A'}, 'Bob': {'age': 22}}, how would you:
 Access Bob’s age.
 Add a grade ‘B’ for Bob.
 Delete Alice’s grade.

students = {'Alice': {'age': 21, 'grade': 'A'}, 'Bob': {'age': 22}}

# Access
print("Displaying Bob's age:")
print(students['Bob']['age'])

# Add
print('\n')
print("Before adding grade for Bob:")
print(students)
students['Bob']['grade'] = 'B'
print("After adding grade for Bob:")
print(students)

# Delete
print('\n')
print("Before deleting grade of Alice:")
print(students)
del students['Alice']['grade']
print("After deleting grade of Alice:")
print(students)

Output:
Displaying Bob's age:
22

Before adding grade for Bob:


{'Alice': {'age': 21, 'grade': 'A'}, 'Bob': {'age': 22}}
After adding grade for Bob:
{'Alice': {'age': 21, 'grade': 'A'}, 'Bob': {'age': 22, 'grade': 'B'}}

Before deleting grade of Alice:


{'Alice': {'age': 21, 'grade': 'A'}, 'Bob': {'age': 22, 'grade': 'B'}}
After deleting grade of Alice:
{'Alice': {'age': 21}, 'Bob': {'age': 22, 'grade': 'B'}}

Page 9 of 16
10. Use defaultdict to count occurrences of letters in "mississippi". Compare with a regular dictionary.

from collections import defaultdict

# defaultdict
counts = defaultdict(int)
for letter in "mississippi":
counts[letter] += 1
print(counts)

print("\n")
# Regular dict (manual check)
counts = {}
for letter in "mississippi":
counts[letter] = counts.get(letter, 0) + 1
print(counts)

Output:
defaultdict(<class 'int'>, {'m': 1, 'i': 4, 's': 4, 'p': 2})

{'m': 1, 'i': 4, 's': 4, 'p': 2}

11. Write python code with step-by-step implementation to remove all items with even values from {'a':
1, 'b': 2, 'c': 3, 'd':4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10}.

my_dict = {'a': 1, 'b': 2, 'c': 3, 'd':4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10}

# Remove even values


to_remove = [k for k, v in my_dict.items() if v % 2 == 0]
for k in to_remove:
my_dict.pop(k)
print(my_dict)

Output:
{'a': 1, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10}
{'a': 1, 'c': 3, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10}
{'a': 1, 'c': 3, 'e': 5, 'g': 7, 'h': 8, 'i': 9, 'j': 10}
{'a': 1, 'c': 3, 'e': 5, 'g': 7, 'i': 9, 'j': 10}
{'a': 1, 'c': 3, 'e': 5, 'g': 7, 'i': 9}

12. Write python code to implement del, pop(), and popitem() in {'a': 1, 'b': 2, 'c': 3, 'd':4, 'e': 5, 'f': 6,
'g': 7, 'h': 8, 'i': 9, 'j': 10}

# Original dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5,
'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10}

# Using del to remove a specific key-value pair


print("Before del:", my_dict)
del my_dict['a'] # Removes the key 'a' and its value
Page 10 of 16
print("After del:", my_dict)

# Using pop() to remove and return a value


print("\nBefore pop():", my_dict)
removed_value = my_dict.pop('b') # Removes 'b' and returns its value
print("Removed value:", removed_value)
print("After pop():", my_dict)

# Using popitem() to remove and return the last inserted item


print("\nBefore popitem():", my_dict)
last_item = my_dict.popitem() # Removes and returns (key, value) of last item
print("Removed item:", last_item)
print("After popitem():", my_dict)

Output:
Before del: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10}
After del: {'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10}

Before pop(): {'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10}
Removed value: 2
After pop(): {'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10}

Before popitem(): {'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10}
Removed item: ('j', 10)
After popitem(): {'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9}

---------------------------------

13. Write a python program using functions to calculate area, perimeter, and volume of a Cube.

def calculate_cube_area(side_length):
return 6 * (side_length ** 2)

def calculate_cube_perimeter(side_length):
return 4 * side_length

def calculate_cube_volume(side_length):
return side_length ** 3

def main():
print("Cube Calculator")
print("--------------")

try:
side = float(input("Enter the side length of the cube: "))
if side <= 0:
print("Error: Side length must be positive.")
return

print(f"\nFor a cube with side length {side}:")


print(f"Surface Area: {calculate_cube_area(side):.2f}")
Page 11 of 16
print(f"Face Perimeter: {calculate_cube_perimeter(side):.2f}")
print(f"Volume: {calculate_cube_volume(side):.2f}")

except ValueError:
print("Error: Please enter a valid number.")

if __name__ == "__main__":
main()

Output:
Cube Calculator
--------------
Enter the side length of the cube: 6

For a cube with side length 6.0:


Surface Area: 216.00
Face Perimeter: 24.00
Volume: 216.00

14. Write a python program using functions to calculate area, perimeter, and volume of a Sphere.

import math

def calculate_sphere_area(radius):
return 4 * math.pi * (radius ** 2)

def calculate_sphere_circumference(radius):
return 2 * math.pi * radius

def calculate_sphere_volume(radius):
return (4/3) * math.pi * (radius ** 3)

def get_positive_input(prompt):
while True:
try:
value = float(input(prompt))
if value <= 0:
print("Error: Radius must be positive. Please try again.")
continue
return value
except ValueError:
print("Error: Please enter a valid number.")

def main():
print("Sphere Calculator")
print("----------------")

radius = get_positive_input("Enter the radius of the sphere: ")

print(f"\nFor a sphere with radius {radius}:")


print(f"Surface Area: {calculate_sphere_area(radius):.2f}")
Page 12 of 16
print(f"Circumference (great circle): {calculate_sphere_circumference(radius):.2f}")
print(f"Volume: {calculate_sphere_volume(radius):.2f}")

if __name__ == "__main__":
main()

Output:
Sphere Calculator
----------------
Enter the radius of the sphere: 5

For a sphere with radius 5.0:


Surface Area: 314.16
Circumference (great circle): 31.42
Volume: 523.60

15. Write a recursive function to compute factorial of n.

def factorial(n):
if n == 0: # Base case
return 1
else:
return n * factorial(n - 1) # Recursive case

n=int(input("Enter a number:"))
print(factorial(n))

Output:
Enter a number: 4
24

Part – C
1. A search for "python" in "I love Python and PYTHON" fails to match all cases. Fix it.
Code:
word = "python"
text = "I love Python and PYTHON"
print(text.count(word)) # Output: 0 (fails)
Answer
(1) Using re.IGNORECASE:
word = "python"
text = "I love Python and PYTHON"
print(len(re.findall(word, text, re.IGNORECASE)))
Output: 2
(2) Using lower():
word = "python"
text = "I love Python and PYTHON"
print(text.lower().count(word.lower()))
Output: 2
Page 13 of 16
2. A script extracts US phone numbers from text but misses formats like (123) 456-7890. Improve the
regex.
Code:
pattern = r'\d{3}-\d{3}-\d{4}' # Only matches 123-456-7890

Answer
Improved Solution:
pattern = r'\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}' # Matches (123) 456-7890, 123.456.7890, etc.

How the Pattern Works


\(? - Optional opening parenthesis ( (escaped with \)
\d{3} - Matches exactly 3 digits (area code)
\)? - Optional closing parenthesis )
[-.\s]? - Optional separator: hyphen -, dot ., or whitespace \s
\d{3} - Matches 3 digits (exchange code)
[-.\s]? - Optional separator (same as above)
\d{4} - Matches 4 digits (line number)

----------------------------------
3. A program to count lines in a file crashes when the file is empty. Analyze the bug and fix it.
Code:
file = open("notes.txt", "r")
lines = file.readlines()
print(f"Total lines: {len(lines)}")
file.close()
Answer
Analyzing for Missing File handling:
 Bug: Fails if notes.txt doesn’t exist or is empty (no explicit error handling).
 Always handle FileNotFoundError and IOError.
 with ensures the file closes automatically.
 Solution: Use try-except and with.
try:
with open("notes.txt", "r") as file:
lines = file.readlines()
print(f"Total lines: {len(lines)}")
except FileNotFoundError:
print("Error: File not found.")
except IOError:
print("Error: Could not read the file.")
Possible Outcomes & Explanations:
(1) File Exists and is Readable
notes.txt Content:
Line 1
Line 2
Line 3
Output:
Total lines: 3
Page 14 of 16
(2) File Does Not Exist
Output:
Error: File not found.

(3) File Exists but is Unreadable


(e.g., no read permissions or corrupted file)
Output:
Error: Could not read the file.

(4) Empty File


notes.txt Content: (0 bytes, no lines)
Output:
Total lines: 0

4. A Python program reads a file data.txt, processes its content (converts text to uppercase), and writes
the result to output.txt. However, the program fails with an error. Analyze the code below and:
 Identify 3 potential bugs.
 Explain how to fix them.
 Write the corrected program.
Code:
file = open("data.txt")
content = file.read()
processed = content.upper()
output = open("output.txt", "r")
output.write(processed)

Answer
1. Identified Bugs:
Missing File Mode in First open():
The input file is opened without specifying a mode ('r' should be explicit).

Incorrect Mode for Output File:


output.txt is opened in read mode ('r') instead of write mode ('w').

Unclosed File Handles:


Neither file is properly closed, risking resource leaks.

2. Fixes:
Add 'r' mode for the input file.
Use 'w' mode for the output file.
Use with statements to auto-close files.

3. Corrected Program:
with open("data.txt", 'r') as file: # Fix 1: Explicit read mode
content = file.read()

processed = content.upper()

with open("output.txt", 'w') as output: # Fix 2: Write mode + Fix 3: 'with' statement
output.write(processed)
Page 15 of 16
Expected Result:
If data.txt exists (e.g., contains "Hello World"):
Creates output.txt with "HELLO WORLD" (uppercase conversion).
Both files are automatically closed after execution (thanks to with).
If data.txt doesn't exist:
Raises FileNotFoundError (can be handled with try-except).
If output.txt exists:
Overwrites the file completely (due to 'w' mode).

Page 16 of 16

You might also like