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

Python Programming Questions Comprehensive Answer

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 views11 pages

Python Programming Questions Comprehensive Answer

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 Questions:

Comprehensive Answers
This document provides detailed answers to the requested Python programming
questions, including explanations, purpose, syntax, and verified code examples.
1. User-Defined Exceptions in Python
What are User-Defined Exceptions?
In Python, user-defined exceptions (also known as custom exceptions) are exceptions
created by programmers to handle specific error conditions that are not covered by
Python's built-in exceptions. They allow developers to define their own error types, making
the code more readable, maintainable, and robust by clearly indicating what went wrong in
a specific part of the application.
Purpose of User-Defined Exceptions
The primary purposes of user-defined exceptions are:
• Clarity and Readability: They provide more meaningful error messages and types,
making it easier to understand the cause of an error compared to generic exceptions.
• Modularity: They allow for more granular error handling. Different parts of an
application can raise and catch specific exceptions relevant to their domain.
• Maintainability: As the application grows, custom exceptions help in organizing error
handling logic, making it easier to modify or extend.
• Robustness: By catching specific custom exceptions, developers can implement precise
recovery strategies for different error scenarios.
Syntax for User-Defined Exceptions
User-defined exceptions are typically created by defining a new class that inherits from
Python's built-in Exception class (or a subclass of Exception ).
Python
class CustomError(Exception):
def __init__(self, message="A custom error occurred"):
[Link] = message
super().__init__([Link])
• class CustomError(Exception): : This line defines a new class CustomError that inherits
from Exception . This inheritance is crucial as it makes CustomError behave like any
other exception in Python.
• def __init__(self, message): : The constructor __init__ is used to initialize the exception. It
typically takes a message argument to provide details about the error.
• super().__init__([Link]) : This calls the constructor of the parent Exception class,
passing the error message. This ensures that the exception is properly initialized and its
message can be accessed when caught.
Easy Way to Learn It
Think of user-defined exceptions as creating your own specialized
error labels. Instead of just saying "something went wrong," you can say "Insufficient
Balance!" or "Invalid Age!" This makes debugging and understanding errors much clearer.
Python Program to Implement InsufficientBalanceError
This program demonstrates a user-defined exception InsufficientBalanceError for validating
ATM withdrawal transactions. If the requested withdrawal amount exceeds the available
balance, this custom exception is raised.
Python
class InsufficientBalanceError(Exception):
"""Exception raised for errors in the balance.

Attributes:
balance -- available balance
amount -- amount requested for withdrawal
message -- explanation of the error
"""
def __init__(self, balance, amount):
[Link] = balance
[Link] = amount
[Link] = f"Insufficient balance: Available={balance}, Requested={a
super().__init__([Link])

def withdraw(balance, amount):


if amount > balance:
raise InsufficientBalanceError(balance, amount)
return balance - amount

# Example Usage:
current_balance = 500
withdrawal_amount = 1000

try:
new_balance = withdraw(current_balance, withdrawal_amount)
print(f"Withdrawal successful. New balance: {new_balance}")
except InsufficientBalanceError as e:
print(f"Transaction failed: {e}")

withdrawal_amount_success = 200
try:
new_balance = withdraw(current_balance, withdrawal_amount_success)
print(f"Withdrawal successful. New balance: {new_balance}")
except InsufficientBalanceError as e:
print(f"Transaction failed: {e}")

Explanation of Syntax:
• class InsufficientBalanceError(Exception): : Defines a new exception class inheriting from
Exception . This is the standard way to create custom exceptions.
• __init__(self, balance, amount) : The constructor takes balance and amount as
arguments, which are specific to this error scenario. It then constructs a descriptive
message .
• super().__init__([Link]) : Calls the constructor of the parent Exception class,
ensuring the error message is properly stored and accessible when the exception is
caught.
• raise InsufficientBalanceError(balance, amount) : When the if condition ( amount > balance )
is met, this statement creates an instance of InsufficientBalanceError with the current
balance and requested amount, and then raises it. This immediately stops the normal
flow of the withdraw function and transfers control to the nearest except block that can
handle InsufficientBalanceError .
• try...except InsufficientBalanceError as e: : This block attempts to execute the withdraw
function. If an InsufficientBalanceError is raised within the try block, the code inside the
except block is executed, and the exception object is assigned to the variable e ,
allowing us to print its descriptive message.
6. Handling Multiple Exceptions Using Multiple except
Blocks
Explanation
In Python, it's common for a block of code to potentially raise different types of exceptions.
To handle these various exceptions gracefully, you can use multiple except blocks
following a single try block. This allows you to provide specific error handling logic for
each type of exception, making your program more robust and user-friendly.
When an exception occurs within the try block, Python checks the except blocks
sequentially from top to bottom. The first except block whose exception type matches the
raised exception (or is a base class of the raised exception) is executed. If no specific except
block matches, and there's a generic except Exception as e: block, it will catch any unhandled
exception.
Easy Way to Learn It
Imagine you have a toolbox, and each except block is a specific tool. If a problem
(exception) arises, you first try to fix it with your specialized tools (e.g., a wrench for a
ValueError , a screwdriver for a ZeroDivisionError ). If none of your specialized tools work, you
then resort to a general-purpose tool (e.g., a hammer for Exception ) as a last resort.
Python Program to Handle Multiple Exceptions
This program demonstrates how to handle ValueError (e.g., invalid input for integer
conversion) and ZeroDivisionError (e.g., division by zero) using separate except blocks.
Python
def multiple_exceptions_demo(val1, val2):
try:
num1 = int(val1) # May raise ValueError
num2 = int(val2) # May raise ValueError
result = num1 / num2 # May raise ZeroDivisionError
print(f"Result: {result}")
except ValueError:
print("Error: Please enter valid integers.")
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except Exception as e: # Generic exception handler
print(f"An unexpected error occurred: {e}")

# Example Usage:
print("\n--- Test Case 1: ZeroDivisionError ---")
multiple_exceptions_demo("10", "0")

print("\n--- Test Case 2: ValueError ---")


multiple_exceptions_demo("abc", "5")

print("\n--- Test Case 3: No Error ---")


multiple_exceptions_demo("20", "4")
print("\n--- Test Case 4: Another ValueError ---")
multiple_exceptions_demo("10", "xyz")

Explanation of Syntax:
• try: : The code that might raise an exception is placed here.
• except ValueError: : This block catches ValueError exceptions. If int(val1) or int(val2) fails
because the input string cannot be converted to an integer, this block executes.
• except ZeroDivisionError: : This block catches ZeroDivisionError exceptions. If num1 /
num2 attempts to divide by zero, this block executes.
• except Exception as e: : This is a generic except block that catches any other exception
not caught by the preceding specific except blocks. It's good practice to include this as
a fallback for unexpected errors. The as e part assigns the exception object to e ,
allowing you to access details about the error.
7. The raise Statement in Python
Purpose of the raise Statement
The raise statement in Python is used to explicitly trigger an exception. When raise is
executed, it interrupts the normal flow of the program and jumps to the nearest except
block that can handle the type of exception being raised. If no suitable except block is
found, the program terminates and prints a traceback.
The raise statement is crucial for:
• Signaling Errors: It allows functions or methods to indicate that an abnormal condition
has occurred, which prevents them from returning an invalid or unexpected result.
• Enforcing Constraints: It can be used to enforce business rules or input validation. For
example, if an age must be within a certain range, raise can be used if the input is
outside that range.
• Propagating Exceptions: If an except block catches an exception but cannot fully
handle it, it can re-raise the same exception or a different one to propagate the error
further up the call stack.
• Creating Custom Exceptions: As seen in Question 1, raise is used to activate user-
defined exceptions.
Syntax for the raise Statement
The basic syntax for the raise statement is:
Python
raise ExceptionType("Error message")

• ExceptionType : This is the class of the exception to be raised (e.g., ValueError ,


TypeError , MyCustomError ).
• "Error message" : An optional string argument that provides a detailed message about
the error. This message is stored in the exception object and can be accessed when the
exception is caught.
You can also raise an already existing exception object:
Python
my_error = ValueError("Something went wrong!")
raise my_error

Or, to re-raise the last exception that occurred in an except block:


Python
try:
# some code
except SomeError:
# partial handling
raise # re-raises the caught exception

Easy Way to Learn It


Think of raise as shouting "STOP! There's a problem!" in your code. You're not just printing
an error message; you're actively telling the program to halt its current operation and find
someone (an except block) who knows how to deal with this specific problem.
Program to Generate an Exception for Invalid Age Input
This program uses the raise statement to generate a ValueError if the provided age is
outside a valid range (0 to 120).
Python
def check_age(age):
if not isinstance(age, (int, float)):
raise TypeError("Age must be a number.")
if age < 0 or age > 120:
raise ValueError("Invalid age: Age must be between 0 and 120.")
print(f"Age {age} is valid.")
# Example Usage:
print("\n--- Test Case 1: Valid Age ---")
try:
check_age(30)
except (ValueError, TypeError) as e:
print(f"Error: {e}")

print("\n--- Test Case 2: Age too low ---")


try:
check_age(-5)
except (ValueError, TypeError) as e:
print(f"Error: {e}")

print("\n--- Test Case 3: Age too high ---")


try:
check_age(150)
except (ValueError, TypeError) as e:
print(f"Error: {e}")

print("\n--- Test Case 4: Invalid Type ---")


try:
check_age("twenty")
except (ValueError, TypeError) as e:
print(f"Error: {e}")

Explanation of Syntax:
• if age < 0 or age > 120: : This condition checks if the age is outside the acceptable range.
• raise ValueError("Invalid age: Age must be between 0 and 120.") : If the condition is true, a
ValueError is explicitly raised with a descriptive message. This stops the check_age
function and signals an error.
• if not isinstance(age, (int, float)): : An additional check for the type of input, raising a
TypeError if the age is not a number.
• try...except (ValueError, TypeError) as e: : The try block attempts to call check_age . If
either a ValueError or TypeError is raised, the corresponding except block catches it,
and the error message is printed.
20. Copying the Contents of One File into Another File
Explanation
Copying the contents of one file to another is a common file operation. In Python, this
typically involves opening the source file in read mode, reading its entire content, and then
opening the destination file in write mode to write the read content into it. It's crucial to
handle potential FileNotFoundError if the source file does not exist.
Easy Way to Learn It
Think of it like taking notes from one notebook and writing them into another. You open the
first notebook, read everything, and then open the second notebook and write down what
you read. You need to make sure the first notebook actually exists before you can read from
it!
Python Program to Copy File Contents
This program copies the content from [Link] to [Link] and then displays the
content of the [Link] .
Python
def copy_file(source_path, destination_path):
try:
# Open the source file in read mode
with open(source_path, 'r') as src_file:
content = src_file.read() # Read all content from the source file

# Open the destination file in write mode


# If the file doesn't exist, it will be created.
# If it exists, its content will be truncated (overwritten).
with open(destination_path, 'w') as dest_file:
dest_file.write(content) # Write the content to the destination file

print(f"Contents successfully copied from '{source_path}' to '{destinati

# Display the copied content from the destination file


print("\n--- Copied Content in Destination File ---")
with open(destination_path, 'r') as dest_file:
print(dest_file.read())

except FileNotFoundError:
print(f"Error: The source file '{source_path}' was not found.")
except Exception as e:
print(f"An unexpected error occurred: {e}")

# Example Usage:
# Create a dummy source file for demonstration
with open("[Link]", "w") as f:
[Link]("This is the original content of the source file.\n")
[Link]("Line 2 of the source file.")
copy_file("[Link]", "[Link]")
copy_file("non_existent_source.txt", "another_destination.txt") # Test FileNotFo

Explanation of Syntax:
• with open(filename, mode) as file_object: : This is the recommended way to open files in
Python. The with statement ensures that the file is automatically closed even if errors
occur. This is crucial for resource management.
• 'r' mode: Opens the file for reading. If the file does not exist, a FileNotFoundError is
raised.
• 'w' mode: Opens the file for writing. If the file exists, its contents are truncated
(emptied). If the file does not exist, a new one is created.
• src_file.read() : Reads the entire content of the file as a single string.
• dest_file.write(content) : Writes the given content string to the file.
• try...except FileNotFoundError: : This block handles the specific case where the
source_path file does not exist, preventing the program from crashing.

21. Creating and Writing Data to a Text File in Python


(Storing Employee Details)
Explanation
Creating a text file and writing data to it is a fundamental operation for data persistence. In
Python, you use the open() function with a write mode ( 'w' or 'a' ) to create or modify
files. When storing structured data like employee details, it's good practice to use a
consistent format, such as Comma Separated Values (CSV), where each line represents a
record and fields are separated by commas.
Easy Way to Learn It
Think of it as filling out a form and then saving it. You decide on the structure of your form
(e.g., Name, ID, Department), then you write each employee's details according to that
structure, and finally, you save the completed forms into a file.
Python Program to Store Employee Details in a File
This program demonstrates how to create a file named [Link] and store employee
details (Name, ID, Department) in a CSV-like format.
Python
def store_employee_details(filename, employees_list):
try:
with open(filename, 'w') as f: # Open in write mode ('w') to create/ove
# Write a header row for clarity
[Link]("Name,ID,Department\n")

# Iterate through the list of employee dictionaries and write each


for emp in employees_list:
[Link](f"{emp['name']},{emp['id']},{emp['dept']}\n")
print(f"Employee details successfully stored in '{filename}'.")

except IOError as e:
print(f"Error writing to file '{filename}': {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")

# Example Employee Data


employees_data = [
{"name": "Alice Smith", "id": "EMP001", "dept": "Human Resources"},
{"name": "Bob Johnson", "id": "EMP002", "dept": "Information Technology"},
{"name": "Charlie Brown", "id": "EMP003", "dept": "Finance"}
]

output_filename = "[Link]"
store_employee_details(output_filename, employees_data)

print("\n--- Content of [Link] ---")


with open(output_filename, 'r') as f:
print([Link]())

Explanation of Syntax:
• with open(filename, 'w') as f: : Opens the file specified by filename in write mode. If
[Link] doesn't exist, it's created. If it does exist, its content is erased before new
data is written.
• [Link]("Name,ID,Department\n") : Writes a header line to the file. The \n at the end adds
a newline character, ensuring the next write operation starts on a new line.
• for emp in employees_list: : Iterates through each employee dictionary in the
employees_list .
• [Link](f"{emp['name']},{emp['id']},{emp['dept']}\n") : Uses an f-string to format the
employee's details into a comma-separated string, followed by a newline character.
This writes one employee record per line.
• try...except IOError as e: : This handles IOError (a subclass of OSError ), which can occur
during file operations (e.g., permission issues, disk full). It's a good practice to catch
specific file-related exceptions.
This concludes the comprehensive answers to your Python programming questions. All
code examples have been verified for correctness. Please let me know if you have any
further questions or require additional clarification.

You might also like