Python Long Ans BCA PDF
Python Long Ans BCA PDF
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.
• The identi er must start with a letter (A-Z, a-z) or an underscore (_).
• 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.
# Valid identifiers:
student_name = "Rakesh" # Starts with letter, uses
underscore
_age = 21 # Starts with underscore, valid
score1 = 89 # Alphanumeric with digit after first
character
• 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.
• 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)
◦ bool (True/False)
◦ str (strings)
• Mutable data types: These allow modi cation of their content after creation without
changing the object’s identity. Examples include:
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.
name1 = "Rakesh"
name2 = name1 # Both name1 and name2 point to the same
string object initially
print("Before modification:")
print("name1:", name1)
print("name2:", name2)
print("\nAfter modification:")
print("name1:", name1) # New string object: "Rakesh Kumar"
print("name2:", name2) # Remains "Rakesh", original string
unchanged
print("\nBefore modification:")
fl
fi
fi
print("list1:", list1)
print("list2:", list2)
print("\nAfter modification:")
print("list1:", list1) # List updated with new element
print("list2:", list2) # Also shows the updated list, same
object
• 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.
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).
• In result2, parentheses change the evaluation order: the addition 3 + 4 happens rst,
producing 7, then multiplied by 5.
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.
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)
• 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.
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.
• 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.
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.
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.
• 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.
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.
'''
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).
"""
• 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.
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.
Escape sequences allow strings to include characters that would otherwise be dif cult to type or
have special meanings.
fi
fi
Python Program Demonstration:
• \n moves the cursor to the next line, so "World!" appears on a new line after "Hello".
• \" 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.
Using these methods avoids manual character manipulation and makes string operations concise
and readable.
# Convert to uppercase
print("Uppercase:", text.upper())
# Convert to lowercase
print("Lowercase:", text.lower())
# Replace substring
new_text = cleaned_text.replace("World", "Python")
print("Replaced string:", new_text)
• 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!".
• strip() removes spaces from the start and end, cleaning the string.
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.
This is a classic problem that tests string manipulation and comparison skills.
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]
# Test cases
words = ["Madam", "Racecar", "Python", "Step on no pets"]
• It removes spaces so that phrases like "Step on no pets" can be correctly identi ed as
palindromes.
• 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.
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.
• continue skips the current iteration and moves to the next iteration.
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.
print()
• 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.
Operations include:
# 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")
# 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:
• remove() deletes by value, pop() deletes by index and returns removed element.
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:
Sets are useful for removing duplicates and performing membership tests ef ciently.
setA = {1, 2, 3, 4, 5}
setB = {4, 5, 6, 7, 8}
# 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:
• 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).
# Creating a tuple
colors = ("red", "green", "blue")
# Accessing elements
print("First color:", colors[0])
Detailed Explanation:
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:
# 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
del student["course"]
---
**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.
---
```python
print("Multiplication table from 1 to 5:")
Detailed Explanation:
Summary:
Nested loops handle complex iteration scenarios, like tables or grids.
Q8.
Answer:
Concept Explanation:
List comprehensions provide a concise way to create lists using a single line expression.
Detailed Explanation:
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.
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:
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.
largest = numbers[0]
smallest = numbers[0]
fi
fi
fi
for num in numbers:
if num > largest:
largest = num
if num < smallest:
smallest = num
Detailed Explanation:
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:
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:
# Input list
data = [10, 20, 30, 40, 50]
Explanation:
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:
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:
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.
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:
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:
Example Program:
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Display results
print("Original:", numbers)
print("Squared:", squared)
print("Evens:", evens)
print("Product:", product)
Explanation:
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:
# mymath.py
def add(a, b):
return a + b
def square(x):
return x * x
Explanation:
• 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.
Continuing with the nal 5 detailed long answer questions for Unit III – Functions, Modules, and
File Handling:
Answer:
Concept Explanation:
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()
Summary:
Aspec
Module Package
t
Folder with
Type Single .py le
__init__.py
Functions/
Scope Multiple modules grouped
classes
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
• 'a' – Append
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.")
Explanation:
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:
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:
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:
# Driver Code
copy_file("input.txt", "output.txt")
Explanation:
• The program uses with open() for both reading and writing.
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.
import math
print(math.sqrt(16))
import math as m
print(m.pow(2, 3))
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.
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:
Example Code:
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:
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.
Concept Explanation:
• 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.")
# Driver Code
a = Dog()
a.sound()
a.bark()
p = Puppy()
p.eat()
p.bark()
sd = SmartDog()
sd.connect()
sd.control()
sd.bark()
Explanation:
Summary:
Inheritance enhances reusability and maintains code structure. Multiple inheritance is powerful but
requires careful design to avoid con icts (method resolution order – MRO).
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 __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:
Summary:
Operator overloading provides clean, intuitive syntax for object operations. It enhances code
readability and mimics built-in types’ behavior.
Answer:
Concept Explanation:
Code Example:
# Driver Code
divide(10, 2)
divide(5, 0)
fi
Explanation:
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:
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:
Summary:
User-de ned exceptions enhance code robustness and make error messages more meaningful for
speci c business logic.
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:
• '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")
Explanation:
Output (Example):
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:
• Automatic le closure
• Cleaner syntax
Code Example:
write_read_file()
Explanation:
Summary:
Using with is a best practice. It simpli es resource management and ensures safe and ef cient le
handling.
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:
Advantages:
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:
• Private members: Not directly accessible outside the class; pre xed with __ (double
underscore).
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())
Explanation:
Answer:
Concept Explanation:
Python allows handling multiple exceptions using different except blocks for:
• General exceptions
• Cleaner debugging
Code Example:
# Driver Code
process_inputs("10", "0")
process_inputs("ten", "5")
process_inputs("10", "5")
Explanation:
• ZeroDivisionError is caught if b is 0.
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