Answer Key
Answer Key
Answer:
Decorators in Python are a way to modify or extend the behavior of a function or method without
modifying its code. They are implemented as functions that take another function as input and return
a function that enhances the original function.
Answer:
Note - Following is one example. Evaluators may allot marks for any suitable example.
Example:
python
Copy
import numpy as np
arr = np.array([1, 2, 3])
print(arr)
Answer:
A set is an unordered collection of unique elements. It is mutable and does not allow duplicate
elements.
Answer:
A tuple is an ordered collection of elements that are immutable. Once created, its elements cannot be
changed.
Example:
python
Copy
my_tuple = (1, 2, 3)
print(my_tuple[0]) # Output: 1
Q5. What is a package in Python?
Answer:
A package in Python is a collection of Python modules (files containing Python code) grouped
together in a directory. It helps in organizing the code in a hierarchical structure.
Answer:
A dictionary is an unordered collection of key-value pairs. Keys must be unique, while values can be
of any data type.
Example:
python
Copy
my_dict = {"name": "John", "age": 25}
print(my_dict["name"]) # Output: John
Q7. Describe the need for catching exceptions using try and except statements.
Answer:
Catching exceptions helps in handling runtime errors gracefully without crashing the program. Using
try and except ensures that the program can continue to run even when errors occur, and you can
handle specific errors with customized messages.
Answer:
The iterative protocol involves objects implementing the __iter__() and __next__() methods to
make an object iterable. Iterators are used to iterate over sequences like lists, tuples, etc.
Example:
def __iter__(self):
return self
def __next__(self):
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
counter = Counter(1, 5)
for number in counter:
print(number)
Q9. Write a Python program to read a text file and count the number of words, lines, and
characters in it. Also, handle cases where the file might not exist.
Answer:
Note- Any suitable program may be consider.
python
Copy
def count_file_contents(filename):
try:
with open(filename, 'r') as file:
lines = file.readlines()
num_lines = len(lines)
num_words = sum(len(line.split()) for line in lines)
num_chars = sum(len(line) for line in lines)
print(f"Lines: {num_lines}, Words: {num_words}, Characters:
{num_chars}")
except FileNotFoundError:
print("File not found.")
count_file_contents("sample.txt")
Q10. Explain the use of regular expressions with suitable examples.
Answer:
Regular expressions (regex) are used to search for patterns within strings. The re module in Python
provides functionality to search, match, and manipulate text based on patterns.
Example:
python
Copy
import re
Q11. What are the access modifiers in Python? How do they help in programming?
Answer:
In Python, access modifiers are used to control the visibility of class attributes and methods. The
common access modifiers are:
Q12. Explain how Python implements inheritance. Write a small program to demonstrate
multiple inheritance.
Answer:
Inheritance allows a class to inherit methods and attributes from another class. Python supports
multiple inheritance, where a class can inherit from more than one class.
Example:
def greet(self):
print(f"Hello, {self.name}")
class Student:
def __init__(self, grade):
self.grade = grade
def show_grade(self):
print(f"Grade: {self.grade}")
g = Graduate("Alice", "A")
g.greet() # Output: Hello, Alice
g.show_grade() # Output: Grade: A
Q13. Write various Python features that make it a popular programming language.
Answer:
1. Simple and Easy to Learn: Python has a clean and readable syntax.
2. Cross-Platform: Python is platform-independent and can run on any operating system.
3. Extensive Libraries: Python has a vast standard library and third-party libraries.
4. Versatile: Python can be used for web development, data analysis, machine learning, and
automation.
5. Interpreted Language: Python code is executed line-by-line, making debugging easier.
6. Dynamic Typing: Python doesn't require explicit declaration of variable types.
Q14. List common Exception types and explain when they occur.
Answer:
Answer:
Example:
python
Copy
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"Hi, my name is {self.name} and I am {self.age} years old.")
p1 = Person("John", 30)
p1.introduce() # Output: Hi, my name is John and I am 30 years old.
Q16. What is the difference between mutable and immutable objects in Python? Provide
examples.
Answer:
Mutable: Objects that can be changed after creation (e.g., lists, dictionaries).
Immutable: Objects that cannot be changed after creation (e.g., strings, tuples).
Example:
python
Copy
# Mutable
lst = [1, 2, 3]
lst[0] = 100 # List can be changed
# Immutable
s = "Hello"
# s[0] = "h" # This would raise an error, strings are immutable
Q17. Given three Points (x1, y1), (x2, y2) and (x3, y3), write a Python program to check if they
are Collinear.
Answer:
Note- Any suitable program may be consider.
python
Copy
def check_collinear(x1, y1, x2, y2, x3, y3):
area = (x1*(y2 - y3) + x2*(y3 - y1) + x3*(y1 - y2))
return area == 0
Q18. How strings are declared and used in Python. Explain len(), lower(), upper(), strip(), and
replace() functions with coding examples.
Answer:
Note- Any suitable program may be consider.
python
Copy
text = " Hello World! "
print(len(text)) # Output: 15
print(text.lower()) # Output: " hello world! "
print(text.upper()) # Output: " HELLO WORLD! "
print(text.strip()) # Output: "Hello World!"
print(text.replace("World", "Python")) # Output: " Hello Python! "
Q19. Design a Python class called Student with attributes for name, roll number, and marks in
three subjects. Implement methods to calculate the total marks, percentage, and grade of the
student. Allow the user to input details for multiple students and display their results.
Answer:
Following program or algorithm or flow chart is acceptable
python
Copy
class Student:
def __init__(self, name, roll_no, marks):
self.name = name
self.roll_no = roll_no
self.marks = marks
def total_marks(self):
return sum(self.marks)
def percentage(self):
return self.total_marks() / 3
def grade(self):
percentage = self.percentage()
if percentage >= 90:
return "A"
elif percentage >= 75:
return "B"
elif percentage >= 60:
return "C"
else:
return "D"
students = []
for _ in range(2):
name = input("Enter student name: ")
roll_no = input("Enter roll number: ")
marks = list(map(int, input("Enter marks in 3 subjects: ").split()))
student = Student(name, roll_no, marks)
students.append(student)