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

Unit 4 Python Programming Answers

Uploaded by

ratchanya07
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 views4 pages

Unit 4 Python Programming Answers

Uploaded by

ratchanya07
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/ 4

Unit 4 – Python Programming

finally:
print("End of program")

8. Write a Python statement to handle division by zero using try and except.
1. What is a text file in Python? How do you open a file in Python for reading?
Python allows handling runtime errors like division by zero using exceptions.
A text file in Python is used to store data in the form of plain text. Use the try-except block to avoid program termination.
It can be opened using the built-in open() function with mode "r". Example:
Example: file = open("sample.txt", "r") opens the file for reading. try:
2. What is the difference between read() and readline() methods in Python? result = 10 / 0
except ZeroDivisionError:
The read() method reads the entire contents of the file as a string. print("Cannot divide by zero")
The readline() method reads only one line from the file at a time.
read() is used for full content, whereas readline() is used for line-by-line reading. 9. Define exception. How is it different from an error?

3. Give a Python statement to open a file named data.txt in write mode. An exception is an event that disrupts the normal flow of a program.
It can be handled using try-except blocks.
To open a file in write mode, use the open() function with "w" mode. Errors, on the other hand, are often critical and may not be handled easily.
This mode creates a new file or overwrites the existing file.
Example: file = open("data.txt", "w"). 10. Define a module in Python.

4. What does the format operator %s do in Python? A module is a file containing Python code (functions, classes, variables).
It allows for logical organization and reuse of code.
The %s format operator is used to insert a string into another string. Modules can be imported using the import keyword in another file.
It is part of Python’s string formatting technique.
Example: print("Hello %s" % name) will print the name in the string. 11. Name any four built-in exceptions in Python.

5. Explain the role of the else block in exception handling. Python has several built-in exceptions for handling common errors.
Examples include ZeroDivisionError, IndexError, TypeError, and ValueError.
The else block runs if no exception occurs in the try block. These help in writing safe and robust programs.
It is placed after all except blocks and before finally.
It helps in writing code that should only run when there are no errors. 12. Write a Python code using try, except, and finally.

6. What is the purpose of sys.argv in Python? These blocks are used for handling and cleaning up after exceptions.
The try block contains risky code, except handles errors, and finally always runs.
sys.argv is a list in Python that stores command-line arguments. Example:
The first element is the script name, and the rest are input values. try:
It helps in passing arguments to a script during execution. x = int("abc")
except ValueError:
7. What does the finally block do in exception handling? Give an example.
print("Error")
The finally block is always executed whether an exception occurs or not. finally:
It is used for cleanup actions like closing files or releasing resources. print("Done")
Example:
13. How do you append data to an existing text file?
To add data to a file without erasing its content, use "a" mode. 19. What is a CSV file? How do you read a CSV file in Python?
This opens the file in append mode, so data is added at the end.
Example: file = open("data.txt", "a") A CSV file stores data in tabular format using commas as separators.
It can be read using Python’s csv module and csv.reader.
14. How can you create a user-defined exception in Python? Mention the basic steps. Example:
import csv
Create a class that inherits from the built-in Exception class. with open("data.csv") as f:
Use the raise keyword to throw the custom exception. reader = csv.reader(f)
Example:
class MyError(Exception): 20. What is a Python module? How do you import a module in Python?
pass
raise MyError("Custom error") A Python module is a file containing code (functions, classes, etc.).
It promotes reusability and better code organization.
15. Is it possible to catch multiple exceptions in a single except block? If yes, how? You can import it using: import module_name.

Yes, multiple exceptions can be caught using a tuple in the except block. PART-B
This allows handling more than one exception type with the same code.
Example: 1. Explain the different modes used in the open() function with examples.
except (ValueError, ZeroDivisionError): Python’s open() function allows opening files in various modes depending on the
print("Handled") operation:
16. What is the output of the program?
try: 1. 'r' – Read mode: Default mode; opens the file for reading. Raises an error if the file
x = int("abc") does not exist.
except ValueError: Example: f = open('data.txt', 'r')
print("Invalid input")
2. 'w' – Write mode: Opens the file for writing. If the file exists, it will be overwritten. If
The string "abc" cannot be converted to an integer. it does not, a new file is created.
Hence, a ValueError is raised and caught by the except block. Example: f = open('data.txt', 'w')
Output: Invalid input
3. 'a' – Append mode: Opens the file for writing, appending content to the end. It does not
17. How do you use command-line arguments to give input to the program? truncate the file.
Command-line arguments are passed when the script is run from the terminal. Example: f = open('data.txt', 'a')
They are accessed using sys.argv, where argv[1] is the first input.
Example: 4. 'x' – Exclusive creation: Creates a new file and raises an error if the file already exists.
import sys Example: f = open('data.txt', 'x')
print(sys.argv[1])
5. 'b' – Binary mode: Used for binary files like images or PDFs.
18. What are command-line arguments in Python? Example: f = open('data.jpg', 'rb')

They are inputs provided to the script during execution from the terminal.
6. 't' – Text mode: Default mode; used for reading or writing text data.
These arguments are stored in a list called sys.argv.
Example: f = open('data.txt', 'rt')
They help in creating flexible and interactive scripts.
7. '+' – Read and write mode: Used with other modes like 'r+', 'w+', or 'a+' to allow both Example: lines = f.readlines()
reading and writing.
Example: f = open('data.txt', 'r+') Use read() when you need the entire content at once, readline() for streaming line-by-line,
and readlines() when you want to process lines in a list format.
These modes can be combined for operations like reading binary data or updating files
without deleting their content. 4. Discuss how command-line arguments are handled using sys.argv[] in Python.
Provide an example program.
2. Write a Python program that reads a text file and counts the number of lines and
words. Command-line arguments allow users to provide input values when executing a Python
script.
The following program demonstrates how to read a text file and count the number of They are accessed via the sys module’s argv list:
lines and words: 1. sys.argv[0] – The name of the script.
2. sys.argv[1:] – Additional arguments passed by the user.
filename = 'sample.txt' Example program:
line_count = 0 import sys
word_count = 0 if len(sys.argv) > 1:
try: for i, arg in enumerate(sys.argv[1:], start=1):
with open(filename, 'r') as file: print(f'Argument {i}: {arg}')
for line in file: else:
line_count += 1 print('No command-line arguments passed.')
words = line.split()
word_count += len(words) This approach is useful in automation and scripting where arguments are passed
print('Total Lines:', line_count) dynamically.
print('Total Words:', word_count)
except FileNotFoundError: 5. Explain exception handling with try, except, else, and finally clauses with
print('The file does not exist.') examples.

Exception handling in Python allows us to catch and manage errors gracefully.


This program opens a file using a context manager, ensuring the file is properly closed 1. try: Block where we write code that might raise an exception.
after use. 2. except: Block that handles the exception if raised.
3. Differentiate between read(), readline(), and readlines() methods in file reading. 3. else: Runs only if no exception occurs in the try block.
4. finally: Runs regardless of whether an exception occurred or not.
Python provides three different ways to read file content: Example:
try:
1. read(): Reads the entire file content into a single string. Use it when the file is small. x = int(input('Enter number: '))
Example: content = f.read() y = 10 / x
except ZeroDivisionError:
2. readline(): Reads the next line from the file, including the newline character. print('Cannot divide by zero')
It can be used in loops to read lines one by one. except ValueError:
Example: line = f.readline() print('Invalid input')
else:
3. readlines(): Reads all lines into a list. Each element in the list is a line from the file. print('Result:', y)
finally: class MyCustomError(Exception):
print('Execution completed') pass
try:
This structure ensures that errors are caught, alternatives are executed, and resources are raise MyCustomError("This is a user-defined error")
cleaned up. except MyCustomError as e:
print("Caught an exception:", e)
6. Write a Python program that handles the division of two numbers and catches Explanation:
division-by-zero errors. - MyCustomError is a user-defined exception that inherits from the base Exception class.
try: - It is raised using raise and caught using try-except.
a = int(input("Enter numerator: ")) 9. Write a program to read and display contents of a CSV file using the csv module.
b = int(input("Enter denominator: ")) import csv
result = a / b with open("students.csv", "r") as file:
print("Result:", result) reader = csv.reader(file)
except ZeroDivisionError: for row in reader:
print("Error: Division by zero is not allowed.") print(", ".join(row))
except ValueError: Explanation:
print("Error: Invalid input, please enter numbers only.") - The csv module is used to read the CSV file.
finally: - Each row is read using a loop and printed after joining with commas.
print("Execution completed.") 10. Write a python code to read a CSV file and calculate the average marks of
Explanation: students stored in it.
- The try block attempts to divide two numbers. import csv
- The except block catches division-by-zero and input errors. total = 0
- The finally block executes regardless of exceptions. count = 0
7. Create a program that handles the File Not Found Error when attempting to with open("students.csv", "r") as file:
open a missing file. reader = csv.reader(file)
try: next(reader) # Skip header
file = open("non_existent_file.txt", "r") for row in reader:
content = file.read() total += int(row[1]) # Assuming marks are in the second column
print(content) count += 1
file.close() average = total / count if count > 0 else 0
except FileNotFoundError: print("Average Marks:", average)
print("Error: The file does not exist.") Explanation:
Explanation: - The program calculates average marks by reading values from a CSV file.
- The program tries to open a non-existent file.
- It skips the header and sums the marks, then computes the average.
- The FileNotFoundError is caught and handled with a user-friendly message.
8. Compare built-in and user-defined exceptions. How can we create a user-defined
exception?
Built-in exceptions are predefined errors in Python like ZeroDivisionError, ValueError,
etc.
User-defined exceptions are created by users to handle specific cases.
Example:

You might also like