0% found this document useful (0 votes)
7 views8 pages

Answer Key

The document provides a comprehensive answer key for Python programming questions covering topics such as decorators, data structures (sets, tuples, dictionaries), exception handling, iterative protocols, regular expressions, access modifiers, inheritance, and common exception types. It includes example code snippets for various concepts and demonstrates how to create classes and handle user input for student records. Additionally, it highlights Python's features that contribute to its popularity as a programming language.

Uploaded by

abhishek.sharma
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)
7 views8 pages

Answer Key

The document provides a comprehensive answer key for Python programming questions covering topics such as decorators, data structures (sets, tuples, dictionaries), exception handling, iterative protocols, regular expressions, access modifiers, inheritance, and common exception types. It includes example code snippets for various concepts and demonstrates how to create classes and handle user input for student records. Additionally, it highlights Python's features that contribute to its popularity as a programming language.

Uploaded by

abhishek.sharma
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/ 8

Answer Key

Q1. What are decorators in Python?

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.

Q2. Give an example of a third-party module of Python.

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)

Q3. Define a set in Python.

Answer:

A set is an unordered collection of unique elements. It is mutable and does not allow duplicate
elements.

Q4. What is a tuple in Python? Give an example.

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.

Q6. What is a dictionary in Python? Give an example.

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.

Q8. Discuss the iterative protocol in Python with an example.

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:

Note- Any suitable program may be consider.


python
Copy
class Counter:
def __init__(self, low, high):
self.current = low
self.high = high

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.

Note- Any suitable program may be consider.

Example:

python
Copy
import re

text = "The rain in Spain"


pattern = r"\b\w+in\b"
matches = re.findall(pattern, text)
print(matches) # Output: ['rain', 'Spain']

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:

 Public: Accessible from anywhere.


 Protected: Indicated by a single underscore _, accessible within the class and its subclasses.
 Private: Indicated by a double underscore __, not accessible outside the class.

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:

Note- Any suitable program may be consider.


python
Copy
class Person:
def __init__(self, name):
self.name = name

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}")

class Graduate(Person, Student):


def __init__(self, name, grade):
Person.__init__(self, name)
Student.__init__(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:

1. ZeroDivisionError: Raised when dividing by zero.


2. FileNotFoundError: Raised when a file or directory is requested but cannot be found.
3. ValueError: Raised when a function receives an argument of the right type but inappropriate
value.
4. IndexError: Raised when trying to access an element at an invalid index in a sequence.
5. KeyError: Raised when a key is not found in a dictionary.
Q15. Explain the concept of classes and objects in Python. Create a class called Person with
attributes name and age, and a method called introduce that prints out the person's name and
age.

Answer:

Example:

Note- Any suitable program may be consider.

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:

Note- Any suitable program may be consider.

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

print(check_collinear(1, 2, 2, 3, 3, 4)) # True

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)

for student in students:


print(f"Student: {student.name}, Roll No: {student.roll_no}")
print(f"Total Marks: {student.total_marks()}")
print(f"Percentage: {student.percentage()}")
print(f"Grade: {student.grade()}")

You might also like