0% found this document useful (0 votes)
4 views11 pages

Python Programming Unit4 Solutions

The document is a question bank for a Python programming course, covering various topics including file handling, functions, exception handling, and file I/O operations. It provides example code snippets for tasks such as reading files, writing to files, and using context managers. Each question is followed by a detailed explanation and code implementation, aimed at enhancing understanding of Python programming concepts.

Uploaded by

tanvirai90807
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)
4 views11 pages

Python Programming Unit4 Solutions

The document is a question bank for a Python programming course, covering various topics including file handling, functions, exception handling, and file I/O operations. It provides example code snippets for tasks such as reading files, writing to files, and using context managers. Each question is followed by a detailed explanation and code implementation, aimed at enhancing understanding of Python programming concepts.

Uploaded by

tanvirai90807
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

PYTHON PROGRAMMING (BCC402)

Unit 4 Important Question Bank & Complete Solutions

Q1. Write a Python program to read the last n lines of a file.

To read the last n lines efficiently, we can read all lines into a list and use Python's negative slicing
( [-n:] ).

def read_last_n_lines(filepath, n):


try:
with open(filepath, 'r') as file:
lines = [Link]()
# Slice the last n lines
last_lines = lines[-n:]
for line in last_lines:
print(line, end='')
except FileNotFoundError:
print("The file was not found.")

# Example usage: read last 3 lines of '[Link]'


# read_last_n_lines('[Link]', 3)

Python Programming (BCC402) | Unit 4 Question Bank Page 1 of 11


Q2. How to use functions defined in [Link] inside [Link]? Explain.

To use functions defined in one file inside another, you use Python's import statement. Python looks for
the imported file in the current directory or system path.

Step 1: Create [Link]

# [Link]
def greet_user(name):
return f"Hello, {name}! Welcome to Python Programming."

def add_numbers(a, b):


return a + b

Step 2: Create [Link] (Same Directory)

# [Link] - Method A: Import the entire module


import library

message = library.greet_user("Vishu")
result = library.add_numbers(10, 20)

print(message) # Hello, Vishu! Welcome to Python Programming.


print("Sum:", result) # Sum: 30

# Method B: Import specific functions directly


from library import greet_user, add_numbers
print(greet_user("Noah"))

Python Programming (BCC402) | Unit 4 Question Bank Page 2 of 11


Q3. Find the largest word present in a file using Python file handling.

def find_longest_word(filepath):
longest_word = ""
try:
with open(filepath, 'r') as file:
for line in file:
# Split line into words and strip punctuation
words = [Link]()
for word in words:
cleaned_word = [Link](".,!?;:()"'")
if len(cleaned_word) > len(longest_word):
longest_word = cleaned_word

if longest_word:
print(f"The longest word is: '{longest_word}' (Length:
{len(longest_word)})")
else:
print("The file is empty.")
except FileNotFoundError:
print("File not found.")

# Example Usage:
# find_longest_word('[Link]')

Python Programming (BCC402) | Unit 4 Question Bank Page 3 of 11


Q4. Construct a program to change the contents of a file by separating each character by
a comma.

This program reads the original contents, joins every single character with a comma, and writes the
modified string back into the file.

def separate_chars_with_comma(filepath):
try:
# Read the current content
with open(filepath, 'r') as file:
content = [Link]()

# Join characters with commas


modified_content = ",".join(content)

# Write back to the file


with open(filepath, 'w') as file:
[Link](modified_content)

print("File updated successfully.")


except FileNotFoundError:
print("File not found.")

Q5. Explain the use of the with construct in Python with an example.

The with statement in Python is used for Resource Management. It simplifies exception handling by
encapsulating common preparation and cleanup tasks.

It acts as a Context Manager which automatically closes the file stream once the block inside the with
statement is exited, even if an exception or error occurs during processing. This prevents resource leaks.

# Using 'with' (Recommended)


with open('[Link]', 'w') as file:
[Link]("Hello World!")
# File is automatically closed here! No [Link]() needed.

# Equivalent code without 'with':


file = open('[Link]', 'w')
try:
[Link]("Hello World!")
finally:
[Link]() # Ensures execution even if write raises an error

Python Programming (BCC402) | Unit 4 Question Bank Page 4 of 11


Q6. How to create a Python file that can be imported as a library as well as run as a
standalone script?

To make a script dual-purpose, you use the special conditional check: __name__ == "__main__" .

• When running directly, Python assigns the string "__main__" to the built-in variable __name__ .
• When imported as a library, __name__ is set to the actual filename (without .py ).

# math_utility.py

def square(x):
return x * x

def cube(x):
return x * x * x

# Standalone testing code block


if __name__ == "__main__":
print("Running script directly as a standalone program...")
test_val = 5
print(f"Square of {test_val} is: {square(test_val)}")

Q7. Describe the difference between import library and from library import * in Python.

• import library : Keeps module names separated. You must access functions using the library
prefix: library.function_name() . This keeps namespaces safe from naming conflicts.
• from library import * : Imports all variables, classes, and functions directly into your current
namespace. You can call them directly without a prefix, but this can cause namespace pollution and
silent naming clashes.

# Safe approach
import math
print([Link](16))

# Risky approach
from math import *
print(sqrt(16)) # Easy to write, but can clash with local functions

Python Programming (BCC402) | Unit 4 Question Bank Page 5 of 11


Q8. Explain the importance of Exception Handling. Explain try-except-finally block with
an example.

Importance: Exception handling allows a program to deal with runtime errors (Exceptions) gracefully
without crashing abruptly, preserving the user experience and clean cleanup of system resources.

• try : Wraps the code that might raise an exception.


• except : Captures and handles specific exceptions if they occur.
• finally : Contains code that always executes, regardless of whether an exception occurred or was
handled. Highly useful for closing open files/connections.

def divide_numbers(a, b):


try:
print("Beginning division...")
result = a / b
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: You cannot divide a number by zero!")
finally:
print("Execution of block is complete.\n")

divide_numbers(10, 0)

Q9. Explain File Input and Output operations.

File I/O operations allow a Python program to interact with external storage systems to preserve data
between executions.

1. Open: Establishes a communication path between your program and the physical file using
open(filename, mode) .

2. Read/Write:
◦ Input (Read): Retrieves data from file to variables via .read() , .readline() ,
or .readlines() .
◦ Output (Write): Sends program variables into file via .write() or .writelines() .

3. Close: Saves files buffer changes and releases system resources using .close() .

Python Programming (BCC402) | Unit 4 Question Bank Page 6 of 11


Q10. Write a Python program to open a text file in write mode, write multiple lines of data
into it, and then read the contents of the file.

filename = "io_demo.txt"

# 1. Open in write ('w') mode and write lines


with open(filename, 'w') as file:
[Link]("Line 1: Python is versatile.\n")
[Link]("Line 2: File Handling is easy.\n")
[Link]("Line 3: Unit 4 studies are going well.\n")

print("Data written successfully!\n" + "-"*35)

# 2. Open in read ('r') mode and display contents


with open(filename, 'r') as file:
content = [Link]()
print("Reading contents of the file:")
print(content)

Q11. Explain the difference between the file modes 'r', 'w', 'a', and 'r+' with suitable
examples for each.

Mode Name File Must Exist? Action on Existing File Pointer Position

'r' Read Yes None (Read-only) Start of file

'w' Write No (creates it) Truncates (deletes) existing content Start of file

'a' Append No (creates it) Keeps content; appends data End of file

'r+' Read/Write Yes Overwrites from start Start of file

# Read Mode
with open('[Link]', 'r') as f:
print([Link]())

# Write Mode - truncates content


with open('[Link]', 'w') as f:
[Link]("New")

# Append Mode - appends to existing text


with open('[Link]', 'a') as f:
[Link]("World")

Python Programming (BCC402) | Unit 4 Question Bank Page 7 of 11


Q12. Write a Python program to count the total number of words, characters, and lines in
a file named [Link].

def analyze_file(filename):
line_count = 0
word_count = 0
char_count = 0

try:
with open(filename, 'r') as file:
for line in file:
line_count += 1
char_count += len(line) # Includes spaces & newlines
words = [Link]()
word_count += len(words)

print(f"Analysis of '{filename}':")
print(f"Total Lines: {line_count}")
print(f"Total Words: {word_count}")
print(f"Total Characters: {char_count}")
except FileNotFoundError:
print(f"Error: '{filename}' does not exist.")

Q13. Explain the seek() and tell() functions in Python file handling with proper examples.

• tell() : Returns the current position of the file pointer (cursor) as an integer representing the byte
offset from the start of the file.
• seek(offset, whence) : Moves the file pointer to a specific location.

◦ whence = 0 (default): start of the file.


◦ whence = 1 : current pointer position.
◦ whence = 2 : end of the file.

with open('seek_demo.txt', 'w') as f:


[Link]("Python")

with open('seek_demo.txt', 'r') as f:


print("Initial position:", [Link]()) # Output: 0
data = [Link](2)
print("Read data:", data) # Output: Py
print("Current position:", [Link]()) # Output: 2

[Link](0) # Seek back to start


print("Position after seek(0):", [Link]()) # Output: 0

Python Programming (BCC402) | Unit 4 Question Bank Page 8 of 11


Q14. Write a Python program that reads a file and prints each line after stripping the
newline (\n) character.

def print_stripped_lines(filename):
try:
with open(filename, 'r') as file:
for line in file:
# rstrip('\n') removes only trailing newline spacing
cleaned_line = [Link]('\n')
print(cleaned_line)
except FileNotFoundError:
print("File not found.")

Q15. Explain how exception handling is used during file operations in Python. Write a
program that handles the error when a file does not exist.

File operations rely on external structures (permissions, directories, paths). If a requested file does not
exist or is locked, Python throws runtime errors that crash programs unless handled using try-except
blocks.

def read_safe_file(filepath):
try:
with open(filepath, 'r') as file:
print([Link]())
except FileNotFoundError:
print(f"Error: The file '{filepath}' could not be located on disk.")
except PermissionError:
print("Error: You do not have permission to read this file.")

Q16. Write a Python program to copy contents of one file into another file.

def copy_file(source_file, destination_file):


try:
with open(source_file, 'r') as src, open(destination_file, 'w') as dest:
content = [Link]()
[Link](content)
print(f"Successfully copied contents to {destination_file}.")
except FileNotFoundError:
print("Source file was not found.")

Python Programming (BCC402) | Unit 4 Question Bank Page 9 of 11


Q17. What is the significance of using the with statement for file handling in Python?
Explain with an example where a file is read using this method.

Significance: Automatically and safely releases file streams (closes files) regardless of execution
exceptions, optimizing computational memory consumption and preventing locks.

# Reading safely using the context manager:


with open('[Link]', 'r') as file:
for line in file:
print([Link]())
# The file is fully closed automatically here

Q18. Write a Python program to read a CSV file and display its contents line by line.

import csv

def read_csv_file(filepath):
try:
with open(filepath, mode='r', newline='') as file:
csv_reader = [Link](file)
print(f"--- Contents of {filepath} ---")
for row in csv_reader:
print(row) # row is returned as a list of string elements
except FileNotFoundError:
print("The CSV file was not found.")

Python Programming (BCC402) | Unit 4 Question Bank Page 10 of 11


Q19. Differentiate between text files and binary files in Python. Provide code examples to
write and read data in both formats.

Feature Text Files Binary Files

Human-readable character encoding (Unicode/


Format Encoded raw bytes (0s and 1s).
ASCII).

Line Continuous; no concept of line


Uses \n or \r\n characters.
Endings endings.

Open 'rb' , 'wb' , 'ab' (appended 'b'


'r' , 'w' , 'a'
Modes mode)

Text File Example:

# Writing and reading text


with open('text_demo.txt', 'w') as f:
[Link]("Text Line Data")

with open('text_demo.txt', 'r') as f:


print([Link]())

Binary File Example:

# Writing and reading raw bytes


binary_data = b"Hello Binary Data"

with open('bin_demo.bin', 'wb') as f:


[Link](binary_data)

with open('bin_demo.bin', 'rb') as f:


print([Link]().decode('utf-8'))

Python Programming (BCC402) | Unit 4 Question Bank Page 11 of 11

You might also like