0% found this document useful (0 votes)
10 views47 pages

Python Long Ans BCA PDF

The document covers fundamental concepts in Python, including identifiers, keywords, data types, operator precedence, built-in functions, string indexing and slicing, multi-line statements, and comments. Each section provides explanations, rules, and Python program demonstrations to illustrate the concepts. The importance of following conventions and understanding these concepts for effective programming in Python is emphasized.

Uploaded by

rsatapathy930
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)
10 views47 pages

Python Long Ans BCA PDF

The document covers fundamental concepts in Python, including identifiers, keywords, data types, operator precedence, built-in functions, string indexing and slicing, multi-line statements, and comments. Each section provides explanations, rules, and Python program demonstrations to illustrate the concepts. The importance of following conventions and understanding these concepts for effective programming in Python is emphasized.

Uploaded by

rsatapathy930
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/ 47

Long Answer Questions (5 Marks)

Unit I: Python Basics and Strings

Q1.

Explain the concept of Python identi ers and keywords. Write a Python program to
demonstrate the use of valid and invalid identi ers.

Answer:

Concept Explanation:
In Python, identi ers are names used to identify variables, functions, classes, or other objects.
These names act as references or labels in the program and must follow certain rules to be valid.

Rules for valid identi ers:

• The identi er must start with a letter (A-Z, a-z) or an underscore (_).

• Subsequent characters can be letters, digits (0-9), or underscores.

• Python identi ers are case-sensitive, meaning Variable and variable are different
identi ers.

• Identi ers cannot be the same as Python keywords or reserved words, which have special
meanings and prede ned purposes in Python syntax.

Keywords are reserved words such as if, else, for, while, def, class, return, and
many others. Python uses these keywords to de ne the structure and syntax of the language. Since
keywords have prede ned functionality, they cannot be used as identi ers for variables or functions.

Using invalid identi ers will lead to syntax errors, which will prevent the program from running.

Python Program Demonstration:

# Valid identifiers:
student_name = "Rakesh" # Starts with letter, uses
underscore
_age = 21 # Starts with underscore, valid
score1 = 89 # Alphanumeric with digit after first
character

print("Student Name:", student_name)


print("Age:", _age)
print("Score:", score1)
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
# Invalid identifiers (uncommenting any of the below lines
will cause errors):

# 1name = "John" # Invalid: starts with a digit


# my-name = "Alice" # Invalid: hyphen is not allowed
# for = 10 # Invalid: 'for' is a reserved
keyword
# class = "Math" # Invalid: 'class' is a reserved
keyword

Detailed Explanation of the Code:

• student_name, _age, and score1 all follow the rules for valid identi ers. They start
with letters or underscores and contain only letters, digits, or underscores thereafter.

• The commented invalid identi ers violate naming rules. For example, 1name starts with a
digit, which is not allowed. my-name contains a hyphen, which is not a valid character in
identi ers.

• Trying to use Python keywords like for or class as variable names will cause syntax
errors because Python reserves those words for control ow or class de nitions.

• This program, when run, prints the valid variables correctly. Any uncommented invalid
identi ers will cause immediate syntax errors during code parsing.

Summary:
Knowing how to properly name variables and avoid reserved keywords is fundamental in Python
programming. Valid identi ers improve code readability and maintainability, while invalid ones
cause errors and confusion. Always choose meaningful, valid names that follow Python’s identi er
conventions.

Q2.

Describe the different Python data types. Write a program demonstrating mutable and
immutable types with examples.

Answer:

Concept Explanation:
Python supports various built-in data types to represent different kinds of values. Understanding
these types helps in managing data effectively and predicting how variables behave during
operations.

Python data types can be broadly categorized as immutable and mutable:

• Immutable data types: Once created, their content cannot be changed. Modifying them
creates a new object instead. Examples include:
fi
fi
fi
fi
fl
fi
fi
fi
◦ int (integer numbers)

◦ float ( oating-point numbers)

◦ bool (True/False)

◦ str (strings)

◦ tuple (ordered, xed collections)

• Mutable data types: These allow modi cation of their content after creation without
changing the object’s identity. Examples include:

◦ list (ordered, changeable collections)

◦ dict (key-value mappings)

◦ set (unordered collections of unique elements)

Understanding whether a type is mutable or immutable is important because it affects how variables
reference data, how functions modify objects passed as arguments, and how memory is managed.

Python Program Demonstration:

# Immutable types example: String

name1 = "Rakesh"
name2 = name1 # Both name1 and name2 point to the same
string object initially

print("Before modification:")
print("name1:", name1)
print("name2:", name2)

# Modify name1 by concatenation (creates a new string object)


name1 = name1 + " Kumar"

print("\nAfter modification:")
print("name1:", name1) # New string object: "Rakesh Kumar"
print("name2:", name2) # Remains "Rakesh", original string
unchanged

# Mutable types example: List

list1 = [10, 20, 30]


list2 = list1 # Both variables point to the same list object

print("\nBefore modification:")
fl
fi
fi
print("list1:", list1)
print("list2:", list2)

# Modify the list by appending an element (modifies original


object)
list1.append(40)

print("\nAfter modification:")
print("list1:", list1) # List updated with new element
print("list2:", list2) # Also shows the updated list, same
object

Detailed Explanation of the Code:

• In the rst part, name1 and name2 initially point to the same string "Rakesh". When
we modify name1 by concatenation, Python creates a new string object "Rakesh
Kumar" and name1 points to it. name2 still points to the original string "Rakesh".
This demonstrates that strings are immutable.

• In the second part, both list1 and list2 reference the same list object in memory.
Modifying list1 by appending an element changes the list itself. Since list2 points to
the same list, it also re ects this change, demonstrating mutability.

Summary:
Understanding data types and their mutability is crucial for writing effective Python programs.
Immutable objects help maintain data integrity by preventing accidental changes, while mutable
objects offer exibility but require careful management to avoid unexpected side effects.

Q3.

Explain operator precedence and associativity in Python. Write a program demonstrating


precedence and associativity with arithmetic operators.

Answer:

Concept Explanation:
In Python, when expressions contain multiple operators, the order of evaluation is controlled by
operator precedence and associativity:

• Operator precedence is a hierarchy that determines which operators are evaluated rst.
Operators with higher precedence are evaluated before operators with lower precedence.

• Associativity de nes the order in which operators of the same precedence are evaluated:
either left-to-right (left-associative) or right-to-left (right-associative).

For example, multiplication (*) and division (/) have higher precedence than addition (+) and
subtraction (-), so they are evaluated rst in an expression without parentheses. Exponentiation
fi
fl
fi
fl
fi
fi
(**) is right-associative, meaning expressions like 2 ** 3 ** 2 are evaluated as 2 ** (3
** 2).

Python Program Demonstration:

# Demonstrating operator precedence and associativity

# Expression 1: multiplication (*) has higher precedence than


addition (+)
result1 = 3 + 4 * 5 # Evaluates as 3 + (4*5) = 3 + 20 = 23

# Expression 2: parentheses override precedence


result2 = (3 + 4) * 5 # Evaluates as 7 * 5 = 35

# Expression 3: exponentiation is right-associative


result3 = 2 ** 3 ** 2 # Evaluates as 2 ** (3 ** 2) = 2 ** 9
= 512

print("3 + 4 * 5 =", result1)


print("(3 + 4) * 5 =", result2)
print("2 ** 3 ** 2 =", result3)

Detailed Explanation of the Code:

• In result1, the multiplication operator * takes precedence over addition +, so 4 * 5 is


evaluated rst, resulting in 20. Then 3 is added to 20.

• In result2, parentheses change the evaluation order: the addition 3 + 4 happens rst,
producing 7, then multiplied by 5.

• In result3, exponentiation operators are evaluated from right to left (right-associative).


So 3 ** 2 is computed rst as 9, then 2 ** 9 equals 512.

• Understanding precedence avoids ambiguity and ensures expressions produce correct


results.

Summary:
Operator precedence and associativity are fundamental concepts to predict and control expression
evaluation order. When in doubt, using parentheses improves clarity and prevents mistakes.

Q4.

What are Python built-in functions? Write a program to demonstrate the use of len(),
type(), int(), and str() built-in functions.
fi
fi
fi
Answer:

Concept Explanation:
Python comes with a rich set of built-in functions available without the need to import any module.
These functions perform common operations and simplify programming by saving time and effort.

• len() returns the length (number of items) of an object, such as a string, list, or tuple.

• type() returns the type of an object, which helps in debugging and understanding data
types.

• int() converts a compatible data type (like a string or oat) into an integer.

• str() converts a data type into a string, useful for concatenating or printing.

Using these built-in functions is essential for data manipulation, type checking, and conversions in
Python programs.

Python Program Demonstration:

# Built-in functions demonstration

name = "Rakesh"
print("Length of string 'name':", len(name)) # Returns
number of characters

age_str = "30"
age = int(age_str) # Converts string to integer
print("Converted integer age:", age)

price = 99.99
print("Type of 'price':", type(price)) # Returns <class
'float'>

score = 95
score_str = str(score) # Converts integer to string
print("Score as string:", score_str)
print("Concatenated message:", "Score: " + score_str)

Detailed Explanation of the Code:

• len(name) counts the number of characters in "Rakesh", which is 6.

• int(age_str) converts the string "30" to the integer 30 so it can be used in


calculations.

• type(price) returns the type float because 99.99 is a oating-point number.


fl
fl
• str(score) converts the integer 95 into the string "95", allowing it to be
concatenated with other strings.

• These functions improve program exibility, error handling, and enable type-safe operations.

Summary:
Mastering built-in functions is critical for ef cient Python programming. They offer a quick,
reliable way to manipulate data and perform standard tasks.

Q5.

Describe string indexing and slicing in Python. Write a program to demonstrate accessing
string characters and extracting substrings using slicing.

Answer:

Concept Explanation:
Strings in Python are sequences of characters stored in a speci c order. Each character in a string
can be accessed using indexing, where the index starts at 0 for the rst character.

Python also supports negative indexing, where -1 refers to the last character, -2 to the second
last, and so forth.

Slicing allows extracting a substring by specifying a range of indices: [start:stop:step].


The slice includes characters from the start index up to but not including the stop index. The
step parameter (optional) determines the interval between characters.

Python Program Demonstration:

text = "Programming"

# Indexing examples
print("First character:", text[0]) # P
print("Last character:", text[-1]) # g
print("Fifth character:", text[4]) # r

# Slicing examples
print("Substring [0:6]:", text[0:6]) # Progra (indexes 0 to
5)
print("Substring [3:8]:", text[3:8]) # gramm (indexes 3 to
7)
print("Substring with step 2:", text[::2]) # Pormig (every
2nd character)
print("Reversed string:", text[::-1]) # gnimmargorP
(reverse order)
fl
fi
fi
fi
Detailed Explanation of the Code:

• text[0] accesses the rst character 'P' because indexing starts at zero.

• text[-1] accesses the last character 'g' by counting backward from the end.

• Slicing with [0:6] extracts characters from index 0 to 5.

• The slice [3:8] extracts characters from index 3 to 7.

• Using a step in slicing, [::2] extracts every second character, useful for patterns or
ltering.

• Reversing a string is done with [::-1], stepping backward one character at a time.

Summary:
Indexing and slicing are powerful tools for working with strings, enabling selective access and
transformation of textual data with concise syntax.

Q6.Explain the concept of multi-line statements in Python.Write a program


demonstrating the use of multi-line statements with backslash and parentheses.

Answer:

Concept Explanation:
Python usually treats each new line as a separate statement. However, sometimes a single logical
statement can be too long to t in one line, and breaking it for readability is necessary.

Python allows multi-line statements using:

1. Backslash (\): A backslash at the end of a line tells Python that the statement continues on
the next line.

2. Parentheses (), brackets [], and braces {}: Statements enclosed within these delimiters
can span multiple lines without the need for backslashes.

Using multi-line statements improves code readability, especially for long expressions or complex
function calls.

Python Program Demonstration:

# Using backslash for multi-line statement


total = 10 + 20 + 30 + \
40 + 50 + 60
print("Total using backslash:", total)
fi
fi
fi
# Using parentheses for multi-line statement
total2 = (10 + 20 + 30 +
40 + 50 + 60)
print("Total using parentheses:", total2)

Detailed Explanation of the Code:

• In the rst example, the backslash \ at the end of the rst line signals that the addition
continues on the next line. Without it, Python would raise a syntax error.

• In the second example, the expression is enclosed in parentheses (). Python automatically
understands that the statement continues inside the parentheses, so no backslash is needed.

• Both approaches produce the same result, but parentheses are often preferred because they
are less error-prone and visually clearer.

Q7. Explain how Python handles comments. Write a program containing single-
line and multi-line comments and explain their use.

Answer:

Concept Explanation:
Comments are non-executable parts of the code that help programmers document their logic and
improve code readability. Python ignores comments during execution.

There are two types of comments in Python:

1. Single-line comments: Start with the hash (#) symbol and continue till the end of the line.
Used to explain single lines or short sections of code.

2. Multi-line comments: Python does not have an of cial multi-line comment syntax but
programmers use multi-line strings enclosed in triple quotes (''' or """) which are
ignored if not assigned or used. These serve as block comments or docstrings.

Comments help others (and your future self) understand the code’s purpose, logic, and ow.

Python Program Demonstration:

# This is a single-line comment explaining the next line


x = 10 # Initialize x with 10

'''
This is a multi-line comment
used to describe a block of code,
usually spanning multiple lines.
'''
fi
fi
fi
fl
"""
Another multi-line comment style
used often for documentation (docstrings).
"""

print("Value of x:", x) # Prints the value of x

Detailed Explanation of the Code:

• The line starting with # is a single-line comment and ignored by the Python interpreter. It
helps describe the purpose of the variable initialization.

• The triple-quoted strings act as multi-line comments but are technically multi-line strings
that are not assigned to any variable or function, so Python ignores them during execution.

• Inline comments can follow code on the same line for quick clari cations, as shown next to
the print statement.

• Using comments properly is essential in any codebase to make the code maintainable and
easier to debug or enhance later.

Summary:
Comments are critical for communication between programmers. Use single-line comments for
brief notes and triple quotes for detailed explanations or block comments.

Q8. What are escape sequences in Python strings? Write a program


demonstrating the use of escape sequences like \n, \t, \\, and \".

Answer:

Concept Explanation:
Escape sequences are special characters in Python strings that represent non-printable or special
formatting characters. They begin with a backslash (\) followed by a character that represents an
action or symbol.

Common escape sequences include:

• \n — newline (moves cursor to the next line)

• \t — tab (adds a horizontal tab space)

• \\ — backslash (prints a single backslash)

• \" — double quote (prints a double quote within a double-quoted string)

Escape sequences allow strings to include characters that would otherwise be dif cult to type or
have special meanings.
fi
fi
Python Program Demonstration:

# Demonstrate escape sequences in strings

print("Hello\nWorld!") # Prints Hello and World on two


lines
print("Column1\tColumn2") # Prints with tab space between
columns
print("This is a backslash: \\") # Prints a single backslash
print("She said, \"Hello!\"") # Prints double quotes
inside string

Detailed Explanation of the Code:

• \n moves the cursor to the next line, so "World!" appears on a new line after "Hello".

• \t inserts a tab space, useful for formatting output in columns.

• \\ escapes the backslash itself, so Python prints a single backslash character.

• \" allows inclusion of double quotes inside a string de ned by double quotes without
ending the string.

Escape sequences are essential for formatting strings in output, le paths, or when dealing with
special characters.

Summary:
Mastering escape sequences helps in writing exible and readable string data, especially for user
interaction and le handling.

Q9. Describe string methods in Python. Write a program using at least four
different string methods such as upper(), lower(), strip(), and replace().

Answer:

Concept Explanation:
Python provides many string methods to manipulate and process string data ef ciently. These
methods are built-in functions that can be called on string objects to perform tasks like case
conversion, trimming spaces, replacing substrings, and more.

Some commonly used string methods include:

• upper() — converts all characters to uppercase

• lower() — converts all characters to lowercase


fi
fl
fi
fi
fi
• strip() — removes whitespace from the beginning and end

• replace(old, new) — replaces occurrences of a substring old with new

Using these methods avoids manual character manipulation and makes string operations concise
and readable.

Python Program Demonstration:

text = " Hello, World! "

print("Original string:", repr(text)) # repr() shows


whitespace visibly

# Convert to uppercase
print("Uppercase:", text.upper())

# Convert to lowercase
print("Lowercase:", text.lower())

# Strip whitespace from both ends


cleaned_text = text.strip()
print("Stripped string:", repr(cleaned_text))

# Replace substring
new_text = cleaned_text.replace("World", "Python")
print("Replaced string:", new_text)

Detailed Explanation of the Code:

• The original string contains leading and trailing spaces; repr() helps visualize these
spaces.

• upper() converts all letters to uppercase, making "Hello, World!" into "HELLO,
WORLD!".

• lower() does the opposite, converting to lowercase.

• strip() removes spaces from the start and end, cleaning the string.

• replace("World", "Python") substitutes the word "World" with "Python",


demonstrating powerful text transformation.

Summary:
String methods are powerful tools for ef cient text processing in Python. Learning them greatly
simpli es common tasks like formatting, cleaning, and modifying strings.
fi
fi
Q10.

Write a Python program to check whether a given string is a palindrome or not. Explain the
logic used in your program.

Answer:

Concept Explanation:
A palindrome is a string that reads the same forward and backward, e.g., "madam", "racecar".
Checking for a palindrome involves comparing the string with its reverse.

The logic involves:

1. Taking the original string.

2. Reversing the string using slicing ([::-1]).

3. Comparing the original string and the reversed string.

4. If both match, the string is a palindrome; otherwise, it’s not.

This is a classic problem that tests string manipulation and comparison skills.

Python Program Demonstration:

def is_palindrome(s):
# Convert string to lowercase to make the check case-
insensitive
s = s.lower()
# Remove spaces to handle multi-word palindromes
s = s.replace(" ", "")
# Reverse the string
rev_s = s[::-1]

# Compare original and reversed strings


if s == rev_s:
return True
else:
return False

# Test cases
words = ["Madam", "Racecar", "Python", "Step on no pets"]

for word in words:


if is_palindrome(word):
print(f"'{word}' is a palindrome.")
else:
print(f"'{word}' is not a palindrome.")

Detailed Explanation of the Code:

• The function is_palindrome converts the input to lowercase for case-insensitive


comparison.

• It removes spaces so that phrases like "Step on no pets" can be correctly identi ed as
palindromes.

• The string is reversed using slicing [::-1].

• The function returns True if the original cleaned string matches its reversed version,
otherwise False.

• The test loop demonstrates the function with several strings, printing whether each is a
palindrome.

Summary:
This program demonstrates essential string operations like case conversion, replacement, slicing,
and comparison to solve a common programming problem.

Got it, Rakesh. Here’s the full 10 Long Answer Questions for Unit II (Control Structures and Data
Structures), each with detailed 300+ word answers including explanations and properly documented
medium-level code.

Unit II: Control Structures and Data Structures


Long Answer Questions (5 Marks)

Q1.

Explain the difference between for and while loops in Python. Write programs to
demonstrate both types of loops, including the use of break and continue statements.

Answer:

Concept Explanation:
Python provides two primary repetition control structures: for and while loops.
fi
• for loop: Iterates over a sequence (like a list, string, or range). The number of iterations is
usually known before entering the loop.

• while loop: Repeats as long as a speci ed condition remains true. Useful when the
number of iterations is unknown beforehand.

break and continue:

• break immediately terminates the loop, exiting the loop block.

• continue skips the current iteration and moves to the next iteration.

Python Program Demonstration:

# Using a for loop with break and continue


print("For loop demo:")
for i in range(1, 6):
if i == 3:
print("Skipping 3")
continue # skip printing 3
if i == 5:
print("Breaking at 5")
break # exit loop when i == 5
print(i)

# Using a while loop with break and continue


print("\nWhile loop demo:")
count = 1
while count <= 6:
if count == 4:
print("Skipping 4")
count += 1
continue # skip 4
if count == 6:
print("Breaking at 6")
break # exit loop
print(count)
count += 1

Detailed Explanation:

• The for loop iterates over numbers 1 to 5. When i is 3, continue skips printing it.
When i reaches 5, break exits the loop.

• The while loop increments a counter from 1 to 6. Similar logic applies: skipping 4 and
breaking at 6.
fi
• for is ideal for nite sequences, while while is useful when loop duration depends on
dynamic conditions.

Summary:
Understanding when and how to use for and while loops and controlling ow with break and
continue is fundamental in programming logic.

Q2.

Explain the else clause used with loops in Python. Provide a code example showing how
else works with a for loop and a while loop.

Answer:

Concept Explanation:
In Python, loops (for and while) can have an optional else clause that executes when the loop
terminates normally, i.e., without encountering a break statement.

• The else block runs after the loop nishes iterating all elements or when the while
condition becomes false.

• If the loop is terminated prematurely with break, the else block is skipped.

This feature is unique and useful for search operations or validation checks.

Python Program Demonstration:

# For loop with else


for num in range(1, 6):
if num == 3:
print("Found 3, breaking the loop")
break
else:
print("Loop completed without break")

print()

# While loop with else


count = 1
while count <= 5:
print(count)
count += 1
else:
print("While loop completed without break")
fi
fi
fl
Detailed Explanation:

• In the for loop, since the loop encounters break at num == 3, the else block does
not execute.

• In the while loop, the loop ends naturally when count > 5, so the else block
executes, printing the message.

• This allows detection of whether the loop was fully completed or interrupted.

Summary:
else in loops offers a clean way to run code after successful completion of the loop, helpful in
search or veri cation tasks.

Q3.

Describe how lists are created and manipulated in Python. Write a program demonstrating
creating a list, accessing elements, slicing, adding and removing elements, and looping
through the list.

Answer:

Concept Explanation:
Lists are mutable, ordered collections that can store heterogeneous elements in Python.

Creating a list: Use square brackets [] with elements separated by commas.

Operations include:

• Access elements by index (list[index])

• Slice parts (list[start:end])

• Add elements with append(), insert()

• Remove elements with remove(), pop()

• Loop over elements using for loops

Python Program Demonstration:

# Creating a list
fruits = ["apple", "banana", "cherry", "date", "elderberry"]

# Access elements
print("First fruit:", fruits[0])
fi
print("Last fruit:", fruits[-1])

# Slicing
print("First three fruits:", fruits[0:3])

# Adding elements
fruits.append("fig")
fruits.insert(2, "blueberry")

print("List after additions:", fruits)

# Removing elements
fruits.remove("banana") # remove by value
popped = fruits.pop(3) # remove by index
print("Removed fruit:", popped)

# Looping
print("Looping through list:")
for fruit in fruits:
print(fruit)

Detailed Explanation:

• List indices start at 0; negative indices start from the end.

• Slicing extracts a sublist.

• append() adds to the end, insert() adds at a speci c position.

• remove() deletes by value, pop() deletes by index and returns removed element.

• Looping lets you process or display list elements.

Summary:
Lists are versatile data structures central to Python programming, allowing easy storage and
manipulation of data.

Q4.

What are sets in Python? Explain set operations with an example including union,
intersection, difference, and symmetric difference.

Answer:

Concept Explanation:
Sets are unordered collections of unique elements in Python.
fi
They support standard mathematical operations:

• Union (|): Elements present in either set

• Intersection (&): Elements common to both sets

• Difference (-): Elements in rst set but not in second

• Symmetric Difference (^): Elements in either set but not in both

Sets are useful for removing duplicates and performing membership tests ef ciently.

Python Program Demonstration:

setA = {1, 2, 3, 4, 5}
setB = {4, 5, 6, 7, 8}

print("Set A:", setA)


print("Set B:", setB)

# Union
print("Union:", setA | setB)

# Intersection
print("Intersection:", setA & setB)

# Difference
print("Difference (A - B):", setA - setB)

# Symmetric Difference
print("Symmetric Difference:", setA ^ setB)

Detailed Explanation:

• Union combines all unique elements from both sets.

• Intersection extracts only common elements.

• Difference returns elements in setA not in setB.

• Symmetric difference excludes common elements, returning only unique ones to each set.

Summary:
Sets provide powerful operations for managing collections with unique elements and performing set
theory calculations.

Q5.
fi
fi
Explain tuples in Python. How do they differ from lists? Write a program to create a tuple,
access elements, and demonstrate tuple immutability.

Answer:

Concept Explanation:
Tuples are ordered, immutable collections in Python.

• Unlike lists, tuples cannot be modi ed after creation (no item assignment, no addition/
removal).

• Useful for xed data sequences or as keys in dictionaries.

Tuples use parentheses () while lists use brackets [].

Python Program Demonstration:

# Creating a tuple
colors = ("red", "green", "blue")

# Accessing elements
print("First color:", colors[0])

# Trying to modify tuple (will cause error)


try:
colors[1] = "yellow"
except TypeError as e:
print("Error:", e)

# Tuples can contain mixed types


mixed = (1, "apple", 3.14)
print("Mixed tuple:", mixed)

Detailed Explanation:

• Attempting to modify tuple elements results in TypeError.

• Tuples are ideal for data that shouldn’t change accidentally.

• They can store heterogeneous data types, like lists.

Summary:
Tuples offer xed, reliable data grouping, unlike lists which are exible and mutable.

Q6.
fi
fi
fi
fl
Describe dictionaries in Python and their basic operations. Write a program to create a
dictionary, add, update, delete key-value pairs, and loop through keys and values.

Answer:

Concept Explanation:
Dictionaries are unordered, mutable collections of key-value pairs.

Keys must be immutable (like strings, numbers, tuples), values can be any type.

Basic operations:

• Creating dictionary with {key: value}

• Adding/updating pairs with dict[key] = value

• Removing pairs with del dict[key] or pop()

• Accessing keys and values with keys(), values(), and looping

Python Program Demonstration:

# Create dictionary
student = {"name": "Alice", "age": 20, "course": "MCA"}

# Access elements
print("Name:", student["name"])

# Add/update key
-value pair
student["grade"] = "A"
student["age"] = 21

print("Updated dictionary:", student)

# Remove key-value pair

del student["course"]

# Loop through keys and values

print("Keys and values:")


for key, value in student.items():
print(f"{key}: {value}")

---

**Detailed Explanation:**
- Dictionaries are fast for lookups by key.
- Adding/updating is done by assignment.
- Deletion can be done via `del` or `pop()`.
- `items()` returns key-value tuples for looping.

---

**Summary:**
Dictionaries store labeled data pairs and provide efficient
data access by keys.

---

### Q7.
**Explain nested loops with an example program to print a
multiplication table from 1 to 5.**

---

### Answer:

**Concept Explanation:**
Nested loops occur when one loop runs inside another loop.

They are useful for working with multi-dimensional data, such


as matrices or tables.

---

Python Program Demonstration:

```python
print("Multiplication table from 1 to 5:")

for i in range(1, 6):


for j in range(1, 6):
print(f"{i*j}", end="\t")
print() # new line after inner loop

Detailed Explanation:

• Outer loop iterates through numbers 1 to 5 (rows).

• Inner loop iterates 1 to 5 (columns).

• Each iteration prints the product, tab-separated.


• print() after inner loop creates a new line for next row.

Summary:
Nested loops handle complex iteration scenarios, like tables or grids.

Q8.

Describe list comprehensions in Python. Write a program to create a list of squares of


numbers from 1 to 10 using list comprehension.

Answer:

Concept Explanation:
List comprehensions provide a concise way to create lists using a single line expression.

Syntax: [expression for item in iterable if condition]

They improve readability and reduce boilerplate code.

Python Program Demonstration:

# List of squares from 1 to 10


squares = [x**2 for x in range(1, 11)]
print("Squares:", squares)

Detailed Explanation:

• Iterates over range(1, 11)

• Computes square x**2 for each element

• Stores result in a new list called squares

• Equivalent to a multi-line loop but compact

Summary:
List comprehensions make list creation clean, ef cient, and readable.

Q9.

Explain the concept of pass statement in Python with a program example. When is it useful?

Answer:
fi
Concept Explanation:
pass is a null statement in Python that does nothing.

It acts as a placeholder where syntax requires a statement but no action is needed yet.

Useful during development or to de ne empty functions, loops, or classes.

Python Program Demonstration:

def placeholder_function():
pass # function not implemented yet

for i in range(3):
pass # loop does nothing

class EmptyClass:
pass # class with no attributes or methods

Detailed Explanation:

• Helps prevent syntax errors when block statements are required.

• Allows code structure to be written rst, implementation added later.

• Avoids indent-related errors.

Summary:
pass is a syntactic placeholder enabling code scaffolding during development.

Q10.

Write a Python program to nd the largest and smallest elements in a list without using built-
in functions like max() and min().

Answer:

Concept Explanation:
Finding max/min involves iterating through the list and comparing each element to track the largest
and smallest values seen so far.

Python Program Demonstration:

numbers = [10, 45, 2, 99, 34, 67, 5]

largest = numbers[0]
smallest = numbers[0]
fi
fi
fi
for num in numbers:
if num > largest:
largest = num
if num < smallest:
smallest = num

print("Largest number:", largest)


print("Smallest number:", smallest)

Detailed Explanation:

• Initialize largest and smallest with rst list element.

• Traverse list, update variables if a larger or smaller element is found.

• Avoids using built-in max() and min() for educational purposes.

Summary:
Manual comparison helps understand the algorithm behind built-in functions.

Got it, Rakesh. I’ll now regenerate all 10 Long Answer Questions (5 Marks) for Unit III –
Functions, Modules, and File Handling, keeping in mind:

• Each answer will be 300+ words.

• Questions will blend concept explanation + medium-level code.

• Code will include proper documentation and meaningful variable names.

• Answers will be exam-oriented, testing conceptual understanding.

✅ Unit III: Long Answer Questions (5 Marks)

Total Questions: 10
Topic Coverage: Functions (basic, advanced, recursion, lambda), Modules, Packages, File
Handling.

Q1. What are user-de ned functions in Python? Explain how to de ne, call, and
return multiple values using a function with an example.
fi
fi
fi
Answer:

Concept Explanation:
In Python, a user-de ned function is a reusable block of code designed to perform a speci c task.
Functions are de ned using the def keyword and can accept input parameters and return results.
They improve code readability, reduce redundancy, and promote modularity.

Python functions can return multiple values as tuples, making them exible for a variety of use
cases.

Syntax:

def function_name(parameters):
# Function body
return value1, value2

Example Program:

# Function to compute the sum and average of a list


def calculate_sum_and_average(numbers):
total = sum(numbers)
avg = total / len(numbers)
return total, avg

# Input list
data = [10, 20, 30, 40, 50]

# Calling the function


total_sum, average = calculate_sum_and_average(data)

# Output the results


print(f"Total Sum: {total_sum}")
print(f"Average: {average}")

Explanation:

• calculate_sum_and_average() accepts a list as a parameter.

• It uses Python’s built-in sum() and len() functions.

• Returns two values: total and average.

• These values are unpacked into separate variables.

Summary:
User-de ned functions are foundational in Python programming. The ability to return multiple
values increases a function's utility and makes the code compact and readable.
fi
fi
fi
fl
fi
Q2. Explain recursive functions in Python. Write a program to nd the factorial
of a number using recursion.

Answer:

Concept Explanation:
A recursive function is a function that calls itself to solve smaller instances of a problem. It consists
of:

1. A base case (termination condition).

2. A recursive case (where the function calls itself).

Python allows recursion up to a certain depth (default: 1000 calls). Recursive logic simpli es
problems like factorial, Fibonacci, etc.

Syntax:

def function_name(parameters):
if base_case_condition:
return base_result
else:
return function_name(modified_parameters)

Example Program:

def factorial(n):
"""
Recursive function to compute factorial.
Base case: factorial(0) = 1
Recursive case: n * factorial(n-1)
"""
if n == 0:
return 1
else:
return n * factorial(n - 1)

# Driver code
number = 5
print(f"Factorial of {number} is: {factorial(number)}")

Explanation:

• factorial(5) calls factorial(4), factorial(3)… until


factorial(0) returns 1.
fi
fi
• Results are stacked and multiplied on the return path.

• This demonstrates divide-and-conquer strategy.

Summary:
Recursion provides elegant solutions for problems with repetitive structure. However, recursive
functions should always include base cases to avoid in nite loops and stack over ow errors.

Q3. Compare iterative and recursive approaches with a program to calculate the
sum of rst n natural numbers using both methods.

Answer:

Concept Explanation:

• Recursion breaks a problem into smaller subproblems and solves each recursively.

• Iteration uses loops like for or while to repeatedly perform a task.

Both methods can be used to compute repetitive tasks like summing a series.

Recursive Approach:

def recursive_sum(n):
"""
Recursively computes sum of first n natural numbers.
Base case: sum of 0 is 0
"""
if n == 0:
return 0
return n + recursive_sum(n - 1)

Iterative Approach:

def iterative_sum(n):
"""
Iteratively computes sum using a loop.
"""
total = 0
for i in range(1, n + 1):
total += i
return total
fi
fi
fl
Driver Code:

n = 10
print("Recursive Sum:", recursive_sum(n))
print("Iterative Sum:", iterative_sum(n))

Comparison:

Aspect Recursion Iteration


Memory
More (due to call stack) Less
Use
More elegant for tree-like More straightforward for
Readability
problems loops
Performance Slower due to overhead Faster and optimized

Summary:
Both recursion and iteration are powerful. Choose recursion for elegance and divide-and-conquer
problems, iteration for speed and simplicity.

Q4. Explain the concept of lambda functions in Python. Write a program using
lambda with map(), filter() and reduce().

Answer:

Concept Explanation:
Lambda functions in Python are anonymous, one-liner functions de ned using the lambda
keyword. They are used where functions are needed brie y, especially with functions like map(),
filter(), and reduce().

Syntax:

lambda arguments: expression

Example Program:

from functools import reduce

# List of numbers
numbers = [1, 2, 3, 4, 5]

# map(): Square each number


squared = list(map(lambda x: x**2, numbers))

# filter(): Keep only even numbers


evens = list(filter(lambda x: x % 2 == 0, numbers))
fl
fi
# reduce(): Multiply all numbers
product = reduce(lambda x, y: x * y, numbers)

# Display results
print("Original:", numbers)
print("Squared:", squared)
print("Evens:", evens)
print("Product:", product)

Explanation:

• map() applies lambda to each element.

• filter() selects elements satisfying the condition.

• reduce() accumulates the result from left to right.

Summary:
Lambda functions make Python concise and powerful, especially when combined with functional
utilities like map(), filter(), and reduce().

Q5. Explain the concept of modules in Python. Write a custom module and show
how to import and use it.

Answer:

Concept Explanation:
A module in Python is a le containing Python de nitions and statements. Using modules allows
you to organize code logically, promote reusability, and manage large projects.

Python has built-in modules (like math, random) and allows custom modules.

Creating a Module:

Create a le named mymath.py:

# mymath.py
def add(a, b):
return a + b

def square(x):
return x * x

Using the Module:


fi
fi
fi
# main.py
import mymath

print("Addition:", mymath.add(10, 5))


print("Square:", mymath.square(6))

Explanation:

• import mymath makes all its functions accessible using


mymath.function_name().

• You can also use from mymath import add to import selectively.

Summary:
Modules improve modularity and maintainability. Python encourages breaking your code into
modules and importing only what's needed.

✅ Rakesh, I’ll continue with Q6 to Q10 in the next response.

Continuing with the nal 5 detailed long answer questions for Unit III – Functions, Modules, and
File Handling:

Q6. What is a Python package? How is it different from a module? Create a


sample package with two modules and use it in a Python program.

Answer:

Concept Explanation:

• A module is a single Python le (.py) containing de nitions and code.

• A package is a directory containing multiple modules and an __init__.py le (which


makes it a package).

Packages allow better code organization, especially for large-scale software.

Step 1: Create the package directory structure:

mypackage/
__init__.py
mathops.py
stringops.py

mathops.py:
fi
fi
fi
fi
def add(a, b):
return a + b
stringops.py:

def to_upper(text):
return text.upper()

Step 2: Using the package in your main le:

from mypackage import mathops, stringops

print("Sum:", mathops.add(3, 7))


print("Uppercase:", stringops.to_upper("hello world"))

Summary:

Aspec
Module Package
t
Folder with
Type Single .py le
__init__.py
Functions/
Scope Multiple modules grouped
classes

Packages support project modularity and are essential in real-world applications.

Q7. What is le handling in Python? Explain reading and writing les with
examples.

Answer:

Concept Explanation:

File handling in Python allows reading from and writing to les using functions like open(),
read(), write(), and close().

Modes:

• 'r' – Read

• 'w' – Write (overwrite)

• 'a' – Append

• 'r+' – Read + Write

Example: Writing to a le
fi
fi
fi
fi
fi
fi
# Writing data to a file
with open("example.txt", "w") as file:
file.write("Hello, Rakesh!\nWelcome to Python file
handling.")

Example: Reading from a le

# Reading data from the file


with open("example.txt", "r") as file:
content = file.read()
print("File Content:\n", content)

Explanation:

• with automatically handles closing the le.

• "w" mode erases previous content.

• File is read entirely using read().

Summary:
File handling is crucial for data persistence. Understanding le modes and methods is vital for le-
based applications like logging, data analysis, and reports.

Q8. Write a program that reads a text le and counts the number of words, lines,
and characters.

Answer:

Program Objective: Process a text le and count:

1. Total lines

2. Total words

3. Total characters

Code:

def analyze_file(filename):
lines = 0
words = 0
characters = 0

try:
with open(filename, "r") as file:
fi
fi
fi
fi
fi
fi
for line in file:
lines += 1
words += len(line.split())
characters += len(line)
except FileNotFoundError:
print("File not found.")
return

print(f"Lines: {lines}")
print(f"Words: {words}")
print(f"Characters: {characters}")

# Driver Code
filename = "sample.txt"
analyze_file(filename)

Explanation:

• Line count is incremented for each iteration.

• Words are counted using split().

• Character count includes spaces and punctuation.

Summary:
This is a classic le handling task testing control structures, string manipulation, and exception
handling.

Q9. Write a program to copy the contents of one text le to another, line by line.

Answer:

Concept Explanation:
File copying involves reading from a source le and writing to a destination le. It’s commonly
used in backups and log le management.

Code:

def copy_file(source, destination):


try:
with open(source, "r") as src, open(destination, "w")
as dest:
for line in src:
dest.write(line)
print("File copied successfully.")
fi
fi
fi
fi
fi
except FileNotFoundError:
print("Source file not found.")

# Driver Code
copy_file("input.txt", "output.txt")

Explanation:

• The program uses with open() for both reading and writing.

• It copies each line using a for loop.

• Exception handling avoids crashing if source is missing.

Summary:
This program reinforces reading and writing streams in le handling—useful in data migration and
le-based apps.

Q10. Explain how import works in Python. What are the different ways to
import modules? Give examples for each.

Answer:

Concept Explanation:
The import statement allows the use of functions and variables from other Python les or
modules. It enables modular programming and code reuse.

1. Import entire module:

import math
print(math.sqrt(16))

2. Import speci c function:

from math import sqrt


print(sqrt(25))

3. Import with alias:

import math as m
print(m.pow(2, 3))

4. Import all names (not recommended):

from math import *


print(sin(3.14))
fi
fi
fi
fi
Summary:

Syntax Description
import module Standard, safe, easy to read
from module import
Import speci c parts
name
import module as alias Useful for long module names
Imports all, prone to namespace
from module import * con icts

Here are the 10 detailed Long Answer Questions with answers for Unit IV – OOP, Exception
Handling, and File Handling of the MCA subject “Programming in Python.” Each answer
includes a conceptual explanation and relevant, well-documented code, crafted to meet exam
expectations.

Q1. What is Object-Oriented Programming (OOP)? Explain its principles with


Python examples.

Answer:

Concept Explanation:

Object-Oriented Programming (OOP) is a paradigm centered around objects that combine data and
functionality. It helps model real-world problems more intuitively.

Core Principles:

1. Encapsulation – Binding data and methods in a class.

2. Abstraction – Hiding internal implementation details.

3. Inheritance – One class acquires properties of another.

4. Polymorphism – Different behaviors with the same method name.

Example Code:

# Encapsulation and Abstraction


class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.__balance = balance # Private variable
fl
fi
def deposit(self, amount):
if amount > 0:
self.__balance += amount

def withdraw(self, amount):


if amount <= self.__balance:
self.__balance -= amount
else:
print("Insufficient funds")

def get_balance(self):
return self.__balance

# Inheritance
class SavingsAccount(BankAccount):
def __init__(self, owner, balance=0, interest=5):
super().__init__(owner, balance)
self.interest = interest

# Polymorphism
def print_balance(account):
print(f"Balance for {account.owner}: ₹
{account.get_balance()}")

# Driver Code
acc = SavingsAccount("Rakesh", 1000)
acc.deposit(500)
acc.withdraw(300)
print_balance(acc)

Explanation:

• __balance is encapsulated and not accessible directly.

• Inheritance is shown via SavingsAccount.

• Polymorphism is demonstrated in print_balance().

Summary:
OOP in Python is simple yet powerful. By implementing classes and objects with encapsulation,
inheritance, and polymorphism, complex programs become modular, readable, and maintainable.

Q2. Write a program in Python that demonstrates different types of inheritance.


Include single, multilevel, and multiple inheritance in your example.
Answer:

Concept Explanation:

Python supports various types of inheritance:

• Single Inheritance: One parent, one child.

• Multilevel Inheritance: A chain of inheritance.

• Multiple Inheritance: One class inherits from two or more parent classes.

Code:

# Single Inheritance
class Animal:
def sound(self):
print("This is an animal.")

class Dog(Animal):
def bark(self):
print("Woof!")

# Multilevel Inheritance
class Puppy(Dog):
def eat(self):
print("Puppy is eating.")

# Multiple Inheritance
class SmartDevice:
def connect(self):
print("Device connected to the internet.")

class SmartDog(Dog, SmartDevice):


def control(self):
print("SmartDog is controlled via app.")

# Driver Code
a = Dog()
a.sound()
a.bark()

p = Puppy()
p.eat()
p.bark()
sd = SmartDog()
sd.connect()
sd.control()
sd.bark()

Explanation:

• Dog inherits Animal: single inheritance.

• Puppy inherits Dog: multilevel.

• SmartDog inherits both Dog and SmartDevice: multiple.

Summary:
Inheritance enhances reusability and maintains code structure. Multiple inheritance is powerful but
requires careful design to avoid con icts (method resolution order – MRO).

Q3. What is operator overloading in Python? Demonstrate operator overloading


using the + operator.

Answer:

Concept Explanation:

Operator Overloading allows custom behavior for operators when used with objects. In Python,
special methods like __add__, __sub__, etc., de ne this behavior.

Example:

class Point:
def __init__(self, x, y):
self.x = x
self.y = y

def __add__(self, other):


return Point(self.x + other.x, self.y + other.y)

def __str__(self):
return f"({self.x}, {self.y})"

# Driver Code
p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2
fl
fi
print("Result of addition:", p3)

Explanation:

• __add__ allows + to add custom objects.

• Without it, p1 + p2 would raise a TypeError.

Summary:
Operator overloading provides clean, intuitive syntax for object operations. It enhances code
readability and mimics built-in types’ behavior.

Q4. De ne exception handling in Python. Write a program to demonstrate


try-except-else-finally blocks with proper explanation.

Answer:

Concept Explanation:

Exception handling gracefully manages runtime errors using:

• try: code that may raise error

• except: handle the error

• else: executes if no error

• finally: always executes

Code Example:

def divide(a, b):


try:
result = a / b
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print(f"Result: {result}")
finally:
print("Operation completed.")

# Driver Code
divide(10, 2)
divide(5, 0)
fi
Explanation:

• The rst call gives a valid result.

• The second catches a division error.

• finally runs both times.

Summary:
Exception handling avoids crashes and improves reliability. Using all blocks (try-except-
else-finally) ensures full control over unexpected issues.

Q5. What are user-de ned exceptions? Write a program that de nes a custom
exception and uses it.

Answer:

Concept Explanation:

User-de ned exceptions let programmers de ne application-speci c errors by subclassing


Exception.

Code:

class AgeTooSmallError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)

def check_age(age):
if age < 18:
raise AgeTooSmallError("Age must be at least 18.")
else:
print("Age accepted.")

# Driver Code
try:
check_age(15)
except AgeTooSmallError as e:
print("Custom Exception Caught:", e)

Explanation:

• Custom class inherits from Exception.


fi
fi
fi
fi
fi
fi
• Raised using raise when age is < 18.

Summary:
User-de ned exceptions enhance code robustness and make error messages more meaningful for
speci c business logic.

Q6. Write a Python program to demonstrate the concept of le handling.


Perform le reading, writing, and appending operations.

Answer:

Concept Explanation:

File handling in Python allows you to create, read, write, and append data to les using built-in
functions such as open(), read(), write(), and the context manager with. File modes:

• 'w': write (overwrites)

• 'a': append

• 'r': read

Code:

# Writing to a file
with open("sample.txt", "w") as file:
file.write("Hello, this is a Python file.\n")
file.write("This is the second line.\n")

# Appending to the same file


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

# Reading the contents


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

Explanation:

• First, a le is created and written to (w).

• Second, data is appended (a).


fi
fi
fi
fi
fi
fi
• Finally, le content is read and printed (r).

Output (Example):

Hello, this is a Python file.


This is the second line.
This line is appended later.

Summary:
Python makes le operations seamless. Using with open() ensures the le is automatically
closed, preventing memory leaks or le corruption.

Q7. What is the purpose of the with keyword in le handling? Demonstrate its
use in a program and explain its advantages.

Answer:

Concept Explanation:

The with keyword is used to wrap le operations in a context manager. It ensures:

• Automatic le closure

• Cleaner syntax

• Protection from errors like leaving les open

Code Example:

# Using with keyword


def write_read_file():
with open("notes.txt", "w") as f:
f.write("Important notes about Python.\n")

with open("notes.txt", "r") as f:


print("File content is:\n", f.read())

write_read_file()

Explanation:

• File is opened using with.

• File gets closed automatically when the block ends.

• There’s no need to explicitly call f.close().


fi
fi
fi
fi
fi
fi
fi
fi
Why it's important:
Without with, forgetting f.close() may lock the le or lead to data corruption.

Summary:
Using with is a best practice. It simpli es resource management and ensures safe and ef cient le
handling.

Q8. De ne the concept of containership in Python OOP. Create a program that


demonstrates an object of one class being used inside another.

Answer:

Concept Explanation:

Containership (also called composition) is a relationship where one class contains an object of
another class. It helps build complex functionality by combining simple classes.

Code Example:

class Engine:
def start(self):
return "Engine started."

class Car:
def __init__(self):
self.engine = Engine() # Containership

def drive(self):
status = self.engine.start()
return f"{status} Car is now driving."

# Driver Code
my_car = Car()
print(my_car.drive())

Explanation:

• Car contains an instance of Engine.

• Car can use Engine’s method start().

Advantages:

• Encourages code reuse


fi
fi
fi
fi
fi
• Promotes modular design

• Enhances testability and exibility

Summary:
Containership is used when a "has-a" relationship exists between classes. It is central to writing
scalable and maintainable object-oriented code.

Q9. Explain the concept of public and private members in Python classes. Show
how name mangling works for private members with an example.

Answer:

Concept Explanation:

• Public members: Accessible from anywhere.

• Private members: Not directly accessible outside the class; pre xed with __ (double
underscore).

• Name Mangling: Internally, Python changes __var to _ClassName__var.

Example:

class Student:
def __init__(self, name, grade):
self.name = name # Public
self.__grade = grade # Private

def show_details(self):
return f"Name: {self.name}, Grade: {self.__grade}"

# Driver Code
s = Student("Rakesh", "A")
print(s.show_details())

# Accessing private member (not recommended)


print(s._Student__grade) # Name mangling

Explanation:

• __grade is a private attribute.

• s._Student__grade accesses it via name mangling.

• Private attributes provide encapsulation and protect internal data.


fl
fi
Summary:
Using private members enforces data hiding. While they can still be accessed, it's discouraged. It’s a
convention to respect object encapsulation in Python.

Q10. Explain exception handling using multiple except blocks. Write a


program that catches multiple types of exceptions with a common structure.

Answer:

Concept Explanation:

Python allows handling multiple exceptions using different except blocks for:

• Speci c error types

• General exceptions

• Cleaner debugging

Code Example:

def process_inputs(a, b):


try:
result = int(a) / int(b)
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Invalid input type. Please enter
numbers.")
except Exception as e:
print("Unexpected Error:", e)
finally:
print("Execution completed.")

# Driver Code
process_inputs("10", "0")
process_inputs("ten", "5")
process_inputs("10", "5")

Explanation:

• ZeroDivisionError is caught if b is 0.

• ValueError is caught if input is non-numeric.


fi
• A generic Exception handles any other issue.

Summary:
Multiple except blocks allow precise and robust error handling. It improves user experience and
helps in debugging by targeting speci c issues.

Let me know if you want me to compile everything into a document or begin formatting for printing
or PDF submission.
fi

You might also like