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

python unit 4 (1)

The document covers file handling and exception management in Python, detailing file types, modes, and methods like ftell() and fseek(). It explains command-line arguments, syntax errors versus exceptions, and provides examples of reading/writing files, counting words, and copying file contents. Additionally, it discusses exception handling using try-except blocks to manage runtime errors.
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 views20 pages

python unit 4 (1)

The document covers file handling and exception management in Python, detailing file types, modes, and methods like ftell() and fseek(). It explains command-line arguments, syntax errors versus exceptions, and provides examples of reading/writing files, counting words, and copying file contents. Additionally, it discusses exception handling using try-except blocks to manage runtime errors.
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

UNIT- IV- FILES AND EXCEPTION HANDLING

PART A ( 2 Marks)
1. Define a file and give its advantages.
➔ A file is a named location on storage media to store data permanently.
Advantages:
 Stores large amounts of data permanently.
 Easy to access and modify anytime.
2. Differentiate text file and binary file.
Text File Binary File
Stores data as readable characters. Stores data in binary (0s and 1s).
Can be opened and read easily in text editors. Needs special programs to read and edit.

3. Write the difference between ftell() and fseek().


 ftell(): Returns the current file pointer position.
 fseek(): Moves the file pointer to a specified location.
4. What is command line argument? Give its purposes.
➔ Arguments passed to a Python script while running it from the command line.
Purpose:
 Provides input without hardcoding.
 Automates and controls script execution.
5. Name the different modes used in file handling.
➔ Modes are:
 'r' (read)
 'w' (write)
 'a' (append)
 'b' (binary)
 '+' (read and write)
6. List down some inbuilt exception.
➔ Examples:
 ZeroDivisionError
 IndexError
 TypeError
 ValueError
 FileNotFoundError
7. What are the distinctions between append and write modes?
 Write ('w') mode: Overwrites the file if it exists.
 Append ('a') mode: Adds data at the end of the file without deleting existing content.
8. What is exception chaining in python? Provide an example.
➔ Exception chaining links one exception to another using raise ... from ....
Example:
try:
x=1/0
except ZeroDivisionError as e:
raise ValueError("Invalid input") from e
9. How do you define a user-defined exception in Python? Write a basic example.
➔ Create a class inheriting from Exception.
Example:
class MyError(Exception):
pass

raise MyError("This is a user-defined error")

10. What is clean-up actions in exception handling? [BL4] [CO4] [2]


➔ Clean-up actions are tasks performed to release resources (like closing files or database connections)
even if an error occurs.
Done using finally block.

Descriptive Questions ( 13 Marks)

1. How can you read and write data in a file using Python? provide source code
examples for both operations.
File Reading and Writing in Python
In Python, file operations like reading and writing are performed using built-in functions.
The important steps are:
1. Open the file (open() function)
2. Read/Write the file
3. Close the file (close() function)
The open() function syntax is:
open(filename, mode)
 filename: Name of the file.
 mode: Mode of opening ('r' - read, 'w' - write, 'a' - append, 'b' - binary etc.)
Writing Data to a File (Write Operation)
Source Code:
# Open a file in write mode
file = open("example.txt", "w")

# Write data into the file


file.write("Hello, this is my first file!\n")
file.write("Python makes file handling easy.\n")

# Close the file


file.close()

print("Data written successfully.")


Explanation:
 open("example.txt", "w") → Opens (creates if not exist) a file in write mode.
 write() → Writes string data to the file.
 close() → Safely closes the file after writing.
Note: If example.txt already exists, it will overwrite the old content.

Reading Data from a File (Read Operation)


Source Code:
# Open the file in read mode
file = open("example.txt", "r")

# Read entire content of the file


content = file.read()

# Print the content


print("The file content is:\n")
print(content)

# Close the file


file.close()
Explanation:
 open("example.txt", "r") → Opens the file for reading.
 read() → Reads the entire file data as a single string.
 print() → Displays the data on the screen.
 close() → Safely closes the file after reading.
Alternative: Using with Statement (Best Practice)
Python provides a better way using with which automatically closes the file:
Writing Example:
with open("example2.txt", "w") as file:
file.write("This is written using with statement.\n")
file.write("No need to manually close the file.")
Reading Example:
with open("example2.txt", "r") as file:
content = file.read()
print(content)
Advantages of with:
 Automatically closes the file.
 Cleaner and more readable code.
 No need to explicitly call close().

2. What are the ftell() and fseek() methods in file handling? Explain with suitable
examples.
ftell() and fseek() Methods in File Handling
In Python, while working with file objects, sometimes you need to:
 Find where you are currently reading/writing inside a file.
 Move to a specific position inside the file.
This is where ftell() and fseek() functions come into play.
1. ftell() Method
➔ The ftell() method returns the current position of the file pointer (cursor) from the beginning of the file,
measured in bytes.
Syntax:
file_object.tell()
➔ tell() is the function we use in Python (equivalent of C's ftell()).
Example:
# Open a file in write mode
file = open("sample.txt", "w")
file.write("Hello World")

# Check the current file pointer position


position = file.tell()
print("Current file pointer position:", position)

file.close()
Output:
Current file pointer position: 11
Explanation:
 After writing "Hello World", the pointer moves 11 bytes forward (each character = 1 byte).
 tell() returns the current byte position.
2. fseek() Method
➔ In Python, seek() function is used to move the file pointer to a specific position.
Syntax:
file_object.seek(offset, whence)
 offset → Number of bytes to move.
 whence → Reference point:
o 0 → Beginning of file (default)
o 1 → Current file position
o 2 → End of file
Example:
# Open a file in read mode
file = open("sample.txt", "r")

# Move to the 6th byte


file.seek(6)

# Read the rest of the file


data = file.read()
print("Data after seeking:", data)

file.close()
Output:
Data after seeking: World
Explanation:
 seek(6) moves the file pointer after "Hello " (including space).
 Reading from there gives "World".
Full Working Program Combining Both
# Create a file and write some data into it
with open("sample.txt", "w") as file:
file.write("Hello World! Welcome to Python file handling.")

# Now open the file for reading


with open("sample.txt", "r") as file:
# 1. Find and print the initial pointer position
position = file.tell()
print("Initial Position:", position)

# 2. Read first 5 characters


data = file.read(5)
print("Data read:", data)

# 3. Find and print the pointer position after reading


position = file.tell()
print("Position after reading 5 characters:", position)

# 4. Move the pointer to 13th byte


file.seek(13)
print("Position after seeking to 13:", file.tell())

# 5. Read next 7 characters from current position


data = file.read(7)
print("Data after seeking:", data)

# 6. Find final position


position = file.tell()
print("Final Position:", position)
Sample Output:
Initial Position: 0
Data read: Hello
Position after reading 5 characters: 5
Position after seeking to 13: 13
Data after seeking: Welcome
Final Position: 20

3. Write a python program to count the number of words in a given text file.
Python Program to Count Number of Words in a Text File
# Step 1: Open the file in read mode
with open("textfile.txt", "r") as file:
# Step 2: Read the content of the file
content = file.read()

# Step 3: Split the content into words


words = content.split()

# Step 4: Count the number of words


word_count = len(words)

# Step 5: Display the word count


print("Total number of words in the file:", word_count)
Sample Content inside textfile.txt:
Python is a powerful programming language. It is easy to learn and fun to use.

Sample Output:
Total number of words in the file: 14

Explanation:
Step Action
1 Open the file textfile.txt in read mode using with (so it closes automatically).
2 Read the whole file content using read().
3 Split the text into words using split() (by default it splits at spaces).
4 Use len() function to count total words.
5 Print the word count result.

Key Points to Score Full Marks:


 Using with open(...) → Good coding practice.
 Using split() → Correct method to separate words.
 Closing file automatically (no close() needed after with).
 Output must be printed clearly.
Extra Tip (Optional for High Score):
You can handle exceptions too, like checking if file exists!
Example with exception handling:
try:
with open("textfile.txt", "r") as file:
content = file.read()
words = content.split()
word_count = len(words)
print("Total number of words in the file:", word_count)
except FileNotFoundError:
print("The file does not exist!")

4. Write a python program to copy the contents of one file to another file and
display the contents.
Copy Contents of One File to Another and Display
# Step 1: Open the source file in read mode
with open("source.txt", "r") as source_file:
# Step 2: Read the content of source file
content = source_file.read()

# Step 3: Open the destination file in write mode


with open("destination.txt", "w") as destination_file:
# Step 4: Write the content into destination file
destination_file.write(content)

# Step 5: Open the destination file again to display contents


with open("destination.txt", "r") as destination_file:
print("Contents of destination file:")
print(destination_file.read())

Suppose your source.txt has this content:


Learning Python is fun.
Practice makes you perfect.

Sample Output:
Contents of destination file:
Learning Python is fun.
Practice makes you perfect.

Explanation:
Step Action
1 Open the source file in read mode.
2 Read the full content of the source file.
3 Open/create a destination file in write mode.
4 Write the read content into the destination file.
5 Open the destination file in read mode and display its contents.

Important Points:
 Use with open(...) to handle files properly (auto-closes file).
 Always read content first before writing to another file.
 Open the destination file again if you want to display its content freshly.

5. Explain the concept of command-line arguments in python and demonstrate


their usage with an example program.
Concept of Command-Line Arguments in Python
 Command-line arguments are the inputs given to a Python program when it is run from the
command line (like terminal, command prompt).
 These arguments allow the user to pass information directly to the program without modifying the
code.
 In Python, the sys module is used to access command-line arguments.
 All the arguments are stored in a list called sys.argv:
o sys.argv[0] → Name of the Python script.
o sys.argv[1] → First argument.
o sys.argv[2] → Second argument, and so on.
Key Points about sys.argv:
 It is a list that contains command-line arguments.
 The first element (sys.argv[0]) is always the script name.
 The arguments are received as strings (even if you enter numbers).
Example Python Program using Command-Line Arguments
# Import sys module
import sys

# Display the number of command-line arguments


print("Total arguments passed:", len(sys.argv))

# Display the list of arguments


print("List of arguments:", sys.argv)
# Access individual arguments
print("Script name:", sys.argv[0])

# Check if user provided at least two arguments


if len(sys.argv) > 2:
print("First argument:", sys.argv[1])
print("Second argument:", sys.argv[2])
else:
print("Not enough arguments provided!")
How to Run This Program (Command Line Execution)
Suppose you saved this program as demo_args.py.
You can run it like this in your terminal/command prompt:
python demo_args.py apple banana
Sample Output:
Total arguments passed: 3
List of arguments: ['demo_args.py', 'apple', 'banana']
Script name: demo_args.py
First argument: apple
Second argument: banana
Explanation:
Element Meaning
sys.argv[0] Script name (demo_args.py)
sys.argv[1] First argument (apple)
sys.argv[2] Second argument (banana)
Python treats all command-line arguments as strings. If you need numbers, you have to manually convert
them using int() or float().
Advantages of Command-Line Arguments:
 Dynamic program behavior without changing code.
 Useful in automation, scripting, and batch processing.
 Helps pass filenames, numbers, options, etc., at runtime.

6. Discuss syntax errors and exceptions in python, providing examples to illustrate


their differences.
Syntax Errors vs Exceptions in Python
Python errors are mainly divided into two categories:
→ Syntax Errors
→ Exceptions (Runtime Errors)
They are different in when and why they occur.

1. Syntax Errors
➔ Syntax errors occur when you write code that does not follow Python’s rules.
➔ These are detected at compile time, before the program runs.
Example of Syntax Error:
# Missing colon (:) after if condition
if 5 > 2
print("Five is greater than two")
Output:
SyntaxError: expected ':'
Explanation:
 Python expects a colon : after if 5 > 2.
 Program won't even start until the syntax is corrected.
Other Common Syntax Errors:
 Missing parentheses.
 Incorrect indentation.
 Misspelled keywords.
2. Exceptions (Runtime Errors)
➔ Exceptions occur while the program is running.
➔ Syntax is correct, but some problem happens during execution (like dividing by zero, file not found,
etc.).
Example of Exception:
# Division by zero
a = 10
b=0
print(a / b)
Output:
ZeroDivisionError: division by zero
Explanation:
 Syntax is correct.
 But during execution, division by zero is mathematically not allowed.
Other Common Exceptions:
 ZeroDivisionError
 ValueError
 FileNotFoundError
 IndexError
 TypeError
Comparison Table: Syntax Error vs Exception
Feature Syntax Error Exception
When it occurs During compilation During runtime
Reason Code structure is wrong Logical error during execution
Example Missing colon, wrong indentation Division by zero, file not found
Handling Must fix before running Can be handled using try-except block

Example Handling Exception using try-except


try:
a=5
b=0
print(a / b)
except ZeroDivisionError:
print("Cannot divide by zero!")
Output:
Cannot divide by zero!
7. What is exception handling in Python, and how does the try-except block work?
provide an example.
What is Exception Handling in Python?
➔ Exception handling is the process of responding to runtime errors (exceptions) gracefully, without
crashing the program.
➔ In Python, we handle exceptions using the try-except block.
Why exception handling?
 To avoid program crashes.
 To give user-friendly error messages.
 To continue running the program even if an error occurs.
How does the try-except block work?
 try block: Write the code that may raise an exception inside this block.
 except block: Write the code to handle the exception if it occurs.
 If no error occurs, except block is skipped.
Basic Syntax of try-except:
try:
# Code that might cause an exception
except ExceptionType:
# Code to handle the exception
Important:
 You can have multiple except blocks for different errors.
 You can use a generic except to catch all errors.
Example Program of try-except
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Please enter only numbers.")
Sample Outputs:
Case 1: (Normal Input)
Enter a number: 10
Enter another number: 2
Result: 5.0
Case 2: (Division by Zero)
Enter a number: 10
Enter another number: 0
Error: Cannot divide by zero!
Case 3: (Invalid Input)
Enter a number: ten
Error: Please enter only numbers.
Explanation:
Step Action
1 Code inside try block is executed.
2 If an error happens, Python jumps to the matching except block.
3 Error message is shown instead of crashing the program.
4 If no error, program continues normally.

8. Explain about raising exceptions with an example program.


Raising Exceptions in Python
 Sometimes, you want to manually raise an error in your program based on a certain condition.
 In Python, you can raise exceptions using the raise keyword.
Why raise exceptions?
 To stop the program when something wrong happens.
 To alert the user with a proper error message.
 To maintain correctness and security of the program.

Syntax of Raising an Exception:


raise ExceptionType("Custom error message")
You can raise built-in exceptions like ValueError, TypeError, etc.,
or even create your own user-defined exceptions.

Example Program: Raising Exception


def check_age(age):
if age < 0:
# Raise an exception if age is negative
raise ValueError("Age cannot be negative!")
else:
print("Age is valid:", age)

try:
user_age = int(input("Enter your age: "))
check_age(user_age)
except ValueError as e:
print("Error:", e)

Sample Outputs:
Case 1: Valid Input
yaml
CopyEdit
Enter your age: 25
Age is valid: 25
Case 2: Invalid Input (Negative Age)
Enter your age: -5
Error: Age cannot be negative!
Explanation:
Step Action
1 The check_age function checks if the age is negative.
2 If yes, it raises a ValueError manually with a custom message.
3 The try-except block catches the raised error and prints it nicely.
Thus, the program does not crash, and user gets a meaningful error message.

Important Points about raise:


 You must specify the type of Exception you want to raise.
 You can also create custom exceptions using classes.
 raise immediately stops the normal flow of the program and jumps to except block.

Conclusion:
 Raising exceptions helps to control the flow of programs when unexpected conditions occur.
 It improves program reliability, readability, and debugging.

9. Discuss about various operations performed in a file by giving examples.


File Operations in Python
In Python, files are used to store data. File handling operations in Python are performed using the open()
function and different file methods. You can read, write, and perform other operations on files like closing
them, appending, or even renaming them.

Basic File Operations in Python


1. Opening a File
o The open() function is used to open a file in various modes:
 'r' → Read mode (default, if not specified)
 'w' → Write mode
 'a' → Append mode
 'rb' → Read mode in binary
 'wb' → Write mode in binary
 'x' → Exclusive creation (fails if the file exists)
Syntax:
file = open("filename.txt", "mode")
2. Reading from a File
o You can read the contents of a file using the following methods:
 read(): Reads the entire file content.
 readline(): Reads one line at a time.
 readlines(): Returns a list of lines.
Example:
with open("example.txt", "r") as file:
content = file.read()
print(content)
3. Writing to a File
o To write to a file, you can use the write() or writelines() methods.
o write() writes a string to the file.
o writelines() writes a list of strings.
Example:
with open("example.txt", "w") as file:
file.write("Hello, Python!\nWelcome to File Handling.")
4. Appending to a File
o Use the a mode to add content to the end of the file without overwriting the existing content.
Example:
with open("example.txt", "a") as file:
file.write("\nAdding this new line to the file.")
5. Closing a File
o After performing any operation on a file, it's important to close the file using the close()
method.
o If you use with open(), the file is automatically closed after the block of code is executed.
Example:
file = open("example.txt", "r")
content = file.read()
file.close() # Closing the file
6. Renaming a File
o You can rename a file using the os.rename() method.
Example:
import os
os.rename("oldfile.txt", "newfile.txt")
7. Removing a File
o The os.remove() method allows you to delete a file.
Example:
import os
os.remove("example.txt")
8. File Seeking (Moving the File Pointer)
o You can use the seek() method to move the file pointer to a specific position.
Example:
with open("example.txt", "r") as file:
file.seek(10) # Move to the 10th byte
print(file.read()) # Read from that position onward
9. File Positioning (tell)
o You can use the tell() method to get the current position of the file pointer.
Example:
with open("example.txt", "r") as file:
file.read(5) # Read first 5 characters
print(file.tell()) # Prints the current position of the file pointer
10. Checking if a File Exists
o Use os.path.exists() to check whether a file exists.
Example:
import os
if os.path.exists("example.txt"):
print("File exists")
else:
print("File does not exist")
Example of Multiple File Operations
import os

# Create a file and write some text


with open("sample.txt", "w") as file:
file.write("Python file handling example.\n")
file.write("This is a second line.\n")

# Append to the file


with open("sample.txt", "a") as file:
file.write("This is an appended line.")

# Read and display the content of the file


with open("sample.txt", "r") as file:
content = file.read()
print(content)

# Get the current position of the file pointer


with open("sample.txt", "r") as file:
print("Current position:", file.tell())
file.read(10)
print("New position after reading 10 characters:", file.tell())

# Rename the file


os.rename("sample.txt", "renamed_sample.txt")

Sample Output:
Python file handling example.
This is a second line.
This is an appended line.
Current position: 0
New position after reading 10 characters: 10

10. Explain about exception chaining in python with an example program.


Exception Chaining in Python
Exception Chaining refers to the process of propagating an original exception while raising a new
exception. This allows you to raise a new exception and preserve the context of the original exception. It
helps to provide additional information or a custom message while maintaining the original traceback.
In Python, exception chaining is done using the raise keyword in the except block with the from keyword.

Syntax for Exception Chaining:


try:
# Some code that may raise an exception
except SomeException as e:
raise NewException("Custom error message") from e
 from e allows the original exception (e) to be associated with the new exception, which makes it
easier to debug by tracking the sequence of exceptions.

Example Program Demonstrating Exception Chaining


def divide_numbers(a, b):
try:
result = a / b
except ZeroDivisionError as e:
raise ValueError("Custom error: Division by zero is not allowed!") from e
except TypeError as e:
raise ValueError("Custom error: Both inputs should be numbers!") from e
return result

try:
print(divide_numbers(10, 0)) # This will raise a ZeroDivisionError
except ValueError as e:
print("Error caught:", e)
print("Original exception:", e.__cause__) # Shows the original exception (ZeroDivisionError)

Explanation of Code:
1. divide_numbers() function:
o Attempts to divide two numbers.
o If a ZeroDivisionError or TypeError occurs, a new ValueError is raised with a custom
message, and the original exception is chained to it using from e.
2. In the try-except block:
o The ValueError is caught, and the original exception (like ZeroDivisionError) is accessed
using the __cause__ attribute.

Sample Output:
Error caught: Custom error: Division by zero is not allowed!
Original exception: division by zero
Explanation of Output:
 When a ZeroDivisionError occurs, the ValueError is raised with a custom message.
 The original exception (ZeroDivisionError) is chained and can be accessed via e.__cause__.
Why Use Exception Chaining?
 Improved Error Debugging: It helps in maintaining the traceback and context of the original
exception, making debugging easier.
 Custom Error Messages: You can raise a new exception with a custom error message while
preserving the original exception's details.
 Clearer Exception Handling: It makes it easier to differentiate between different errors and take
appropriate action.
Part – C (15 marks)
1. Discuss the python codes to print try, except and finally block
statements.
Understanding Try, Except, and Finally in Python
In Python, exception handling is done using the try, except, and finally blocks. These blocks allow you to
handle errors gracefully and ensure that certain code always runs, regardless of whether an exception
occurred.
Syntax of Try, Except, and Finally:
try:
# Code that might raise an exception
except SomeException as e:
# Code to handle the exception
finally:
# Code that will always run (used for cleanup actions)

Explanation of Each Block:


1. try Block:
o This block contains the code that may raise an exception.
o If no exception occurs, the program executes the code normally.
2. except Block:
o This block is executed if an exception occurs in the try block.
o You can specify different exception types to handle different errors.
3. finally Block:
o This block contains code that will always run, whether an exception occurs or not.
o It is typically used for cleanup actions, like closing files or releasing resources.

Example Program Demonstrating Try, Except, and Finally


def division(a, b):
try:
print("Trying to divide", a, "by", b)
result = a / b
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except TypeError:
print("Error: Both inputs should be numbers!")
finally:
print("This block always runs, regardless of an exception.")

# Example 1: Normal division


print("Example 1:")
division(10, 2)

# Example 2: Division by zero


print("\nExample 2:")
division(10, 0)

# Example 3: Invalid input (string instead of number)


print("\nExample 3:")
division(10, "a")

Explanation of Code:
 try Block:
o Tries to divide a by b. If b is zero, a ZeroDivisionError occurs.
o If a or b is not a number, a TypeError will occur.
 except Blocks:
o If a ZeroDivisionError occurs, it will print a specific error message.
o If a TypeError occurs, it will print a different error message.
 finally Block:
o This block will always run after the try and except blocks, regardless of whether an exception
occurred or not. It's used here to print a cleanup message.
Sample Output:
Example 1:
Trying to divide 10 by 2
This block always runs, regardless of an exception.

Example 2:
Trying to divide 10 by 0
Error: Cannot divide by zero!
This block always runs, regardless of an exception.

Example 3:
Trying to divide 10 by a
Error: Both inputs should be numbers!
This block always runs, regardless of an exception.

Explanation of Output:
1. In Example 1, the division works fine, and the finally block is executed after the division.
2. In Example 2, since we're dividing by zero, a ZeroDivisionError is caught, and the finally block is
executed after the error message is printed.
3. In Example 3, a TypeError occurs (since we're dividing a number by a string), and the finally block
is executed after the error message.

Key Points:
 The finally block is guaranteed to run, even if an exception occurs.
 You can have multiple except blocks for different types of exceptions.
 If no exception occurs, both try and finally will execute, and the except block will be skipped.
2. Write a python program that prompts the user to enter an integer and raises a ValueError if the
input is not a valid integer.
Python program that prompts the user to enter an integer and raises a ValueError if the input is not a valid
integer:
def get_integer_input():
try:
# Prompt user for input
user_input = input("Please enter an integer: ")

# Try converting input to an integer


number = int(user_input)
print(f"You entered the integer: {number}")

except ValueError:
# Raise ValueError if input is not a valid integer
print("Error: The input is not a valid integer!")
raise ValueError("Invalid input: Please enter a valid integer.")

# Call the function to get user input


get_integer_input()
Explanation:
1. The input() function prompts the user to enter a value.
2. The int() function tries to convert the entered value to an integer.
o If the conversion is successful, it prints the integer.
3. If the input cannot be converted to an integer (e.g., the user enters a string), a ValueError is raised,
and an error message is displayed.
4. The raise ValueError() explicitly raises a ValueError if the input is invalid.
Sample Output:
Valid Input:
Please enter an integer: 42
You entered the integer: 42
Invalid Input (String):
Please enter an integer: hello
Error: The input is not a valid integer!
Traceback (most recent call last):
File "program.py", line 12, in <module>
get_integer_input()
File "program.py", line 8, in get_integer_input
raise ValueError("Invalid input: Please enter a valid integer.")
ValueError: Invalid input: Please enter a valid integer.
3. Write a python program that reads a file and handles a FileNotFoundError if the file does not exist.
Python program that reads a file and handles a FileNotFoundError if the file does not exist:
def read_file(filename):
try:
# Try to open and read the file
with open(filename, 'r') as file:
content = file.read()
print("File content:\n", content)

except FileNotFoundError:
# Handle the case where the file does not exist
print(f"Error: The file '{filename}' does not exist!")
raise FileNotFoundError(f"The file '{filename}' was not found.")

# Ask the user for the file name


file_name = input("Please enter the file name to read: ")
read_file(file_name)
Explanation:
1. The function read_file(filename) tries to open the specified file in read mode ('r').
2. If the file exists, the content is read and printed.
3. If the file doesn't exist, a FileNotFoundError is raised, and an appropriate error message is
displayed.
Sample Output:
Case 1: File exists:
Please enter the file name to read: example.txt
File content:
This is an example file.
Here is some content in it.
Case 2: File does not exist:
Please enter the file name to read: non_existing_file.txt
Error: The file 'non_existing_file.txt' does not exist!
Traceback (most recent call last):
File "program.py", line 15, in <module>
read_file(file_name)
File "program.py", line 9, in read_file
raise FileNotFoundError(f"The file '{filename}' was not found.")
FileNotFoundError: The file 'non_existing_file.txt' was not found.
Explanation of the Output:
 Case 1: The file exists, so the program reads and prints its content.
 Case 2: The file does not exist, so a FileNotFoundError is raised, and an error message is displayed.
4. Write a Python program that attempts to access an index in a list and handles an IndexError
exception if the index is out of range.
Python program that attempts to access an index in a list and handles an IndexError exception if the index
is out of range:
def access_list_element(my_list, index):
try:
# Try to access the element at the specified index
element = my_list[index]
print(f"The element at index {index} is: {element}")

except IndexError:
# Handle the case where the index is out of range
print(f"Error: Index {index} is out of range for the list!")
raise IndexError(f"Index {index} is out of range for the list.")

# Sample list
sample_list = [10, 20, 30, 40, 50]

# Ask the user for an index


index = int(input("Enter the index to access: "))
access_list_element(sample_list, index)
Explanation:
1. access_list_element() function takes a list and an index as input.
2. The program attempts to access the element at the specified index.
3. If the index is valid, it prints the element at that index.
4. If the index is out of range (i.e., greater than the list length), an IndexError is raised, and an error
message is displayed.
Sample Output:
Case 1: Valid Index
Enter the index to access: 2
The element at index 2 is: 30
Case 2: Invalid Index (Out of Range)
Enter the index to access: 7
Error: Index 7 is out of range for the list!
Traceback (most recent call last):
File "program.py", line 14, in <module>
access_list_element(sample_list, index)
File "program.py", line 7, in access_list_element
raise IndexError(f"Index {index} is out of range for the list.")
IndexError: Index 7 is out of range for the list.
Explanation of the Output:
 Case 1: When a valid index (e.g., 2) is entered, it correctly displays the element at that index.
 Case 2: When an invalid index (e.g., 7) is entered, an IndexError is raised, and an error message is
displayed.

You might also like