Q1.
Attempt any FIVE of the following: (10 Marks)
a) Name different modes of Python.
Ans) Python can be used in:
Interactive Mode
Script Mode
b) Give membership operators in Python.
Ans)Membership operators in Python are:
in
not in
c) Explain the role of indentation in Python.
Ans) Indentation in Python is crucial for defining the structure of code blocks. It
determines the grouping of statements within loops, conditional statements,
and function definitions.
d) List any four data structures used in Python.
Ans)Four data structures used in Python are:
List
Tuple
Set b
Dictionary
e) Define class and object in Python.
Ans) Class: A class is a blueprint for creating objects. It defines the attributes
and methods that objects of that class will have.
Object: An object is an instance of a class. It is a concrete entity that has
attributes and behaviors defined by the class.
f) What is data hiding? Mention two advantages.
Ans)Data hiding is a concept where the internal data of an object is hidden
from the outside world, and access to it is restricted through methods.
Advantages of data hiding:
It helps in achieving data security by preventing unauthorized access.
It reduces the complexity of the system by hiding unnecessary details.
g) Write syntax of fopen() in Python file handling.
Ans)The syntax of fopen() in Python file handling is actually the open()
function:
open(filename, mode)
Q2. Attempt any THREE of the following: (12 Marks)
a) Write a Python program to display the following pattern:
Python
2
468
10 12 14 16 18
Python
num = 2
for i in range(1, 4):
for j in range(i):
print(num, end=" ")
num += 2
print()
b) Explain four built-in list functions with examples.
Ans)Four built-in list functions with examples:
append(): Adds an element to the end of the list.
Python
my_list = [1, 2, 3]
my_list.append(4) # my_list is now [1, 2, 3, 4]
insert(): Inserts an element at a specific index.
Python
my_list = [1, 2, 3]
my_list.insert(1, 5) # my_list is now [1, 5, 2, 3]
remove(): Removes the first occurrence of an element.
Python
my_list = [1, 2, 3, 2]
my_list.remove(2) # my_list is now [1, 3, 2]
pop(): Removes and returns the element at a specific index (or the last element
if no index is given).
Python
my_list = [1, 2, 3]
popped_element = my_list.pop(1) # popped_element is 2, my_list is now [1, 3]
c) Write a Python program to find the factorial of a number using a function.
Ans)Python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
num = 5
result = factorial(num)
print("Factorial of", num, "is", result)
d) Write a Python program to create a class 'STUDENT' with Roll No and Name
and display its contents.
Ans)
Python
class STUDENT:
def __init__(self, roll_no, name):
self.roll_no = roll_no
self.name = name
def display_student(self):
print("Roll No:", self.roll_no)
print("Name:", self.name)
# Create an object of STUDENT class
student1 = STUDENT(101, "Alice")
# Display student details
student1.display_student()
Q3. Attempt any THREE of the following: (12 Marks)
a) Explain membership and identity operators with examples.
Ans)
Membership Operators:
in: Checks if a value is present in a sequence. Example: "a" in "apple" (returns
True)
not in: Checks if a value is not present in a sequence. Example: "b" not in
"apple" (returns True)
Identity Operators:
is: Checks if two variables refer to the same object in memory. Example:
Python
x = [1, 2]
y=x
z = [1, 2]
print(x is y) # True
print(x is z) # False (different objects, same content)
is not: Checks if two variables do not refer to the same object. Example: x is not
z (returns True in the above example)
b) Explain readline() and readlines() functions in file handling.
Ans)readline(): Reads a single line from the file. If the end of the file is reached,
it returns an empty string.
readlines(): Reads all lines from the file and returns them as a list of strings.
c) Write a Python program to create and access set elements.
Python
# Creating a set
my_set = {1, 2, 3, 4, 5}
# Accessing set elements (Note: Sets are unordered, so you can't access by
index)
for element in my_set:
print(element)
# Adding elements
my_set.add(6)
print(my_set)
# Removing elements
my_set.remove(3) # Raises error if element is not present
print(my_set)
my_set.discard(7) # Does not raise error if element is not present
print(my_set)
d) Describe the self parameter in Python classes with example.
Ans)
The self parameter is a reference to the current instance of the class. It is
automatically passed as the first argument to any method defined within the
class. It allows you to access the attributes and methods of the object within
the class.
Example:
Python
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print(f" {self.name} says Woof!")
my_dog = Dog("Buddy", "Golden Retriever")
my_dog.bark() # Output: Buddy says Woof!
In this example, self in __init__ is used to assign the name and breed to the
specific dog object being created, and in bark, it's used to access the dog's
name.
Q4. Attempt any THREE of the following: (12 Marks)
a) Explain method overloading and overriding in Python.
Ans)
Method Overloading: While Python doesn't support traditional method
overloading like some other languages (defining multiple methods with the
same name but different parameter lists in the same class), it can be achieved
through techniques like default arguments or variable-length arguments.
Method Overriding: Method overriding occurs when a subclass provides a
different implementation of a method that is already defined in its superclass.
The method in the subclass "overrides" the method in the superclass.
b) Explain if-else and if-elif-else decision-making statements with examples.
Ans)
if-else: Executes one block of code if a condition is true and another block if it's
false.
Python
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
if-elif-else: Used for multiple conditions. It checks conditions sequentially, and if
one is true, it executes the corresponding block. The else block (if present) is
executed if none of the conditions are true.
Python
grade = 75
if grade >= 90:
print("A")
elif grade >= 80:
print("B")
elif grade >= 70:
print("C")
else:
print("Fail")
c) Explain any four file modes in Python.
Ans)
Four file modes in Python:
'r': Read mode (default). Opens the file for reading.
'w': Write mode. Opens the file for writing. If the file exists, it overwrites it. If it
doesn't exist, it creates a new file.
'a': Append mode. Opens the file for writing, but it appends new data to the
end of the file without overwriting the existing content.
'b': Binary mode. Used to open files in binary mode (e.g., for images, audio
files). It can be combined with other modes like 'rb' (read binary) or 'wb' (write
binary).
d) Write a Python program to read from one file and write the same content
into another file.
Python
try:
# Read from file1.txt
with open("file1.txt", "r") as file1:
content = file1.read()
# Write to file2.txt
with open("file2.txt", "w") as file2:
file2.write(content)
print("Content copied successfully!")
except FileNotFoundError:
print("Error: One or both files not found.")
except Exception as e:
print(f"An error occurred: {e}")
e) Write a program that accepts a string and counts uppercase and lowercase
letters.
Ans)
Python
def count_case(text):
upper_count = 0
lower_count = 0
for char in text:
if char.isupper():
upper_count += 1
elif char.islower():
lower_count += 1
return upper_count, lower_count
string = input("Enter a string: ")
upper, lower = count_case(string)
print("Uppercase letters:", upper)
print("Lowercase letters:", lower)
Q5. Attempt any TWO of the following: (12 Marks)
a) Write a Python program to create a class 'Diploma' and its subclasses 'CO'
and 'IF' using inheritance.
Ans)
Python
class Diploma:
def __init__(self, branch):
self.branch = branch
def display_branch(self):
print("Diploma Branch:", self.branch)
class CO(Diploma):
def __init__(self):
super().__init__("Computer Engineering")
def display_specialization(self):
print("Specialization: CO")
class IF(Diploma):
def __init__(self):
super().__init__("Information Technology")
def display_specialization(self):
print("Specialization: IF")
# Create objects
co_student = CO()
if_student = IF()
# Access methods
co_student.display_branch() # Calls Diploma's method
co_student.display_specialization()
if_student.display_branch() # Calls Diploma's method
if_student.display_specialization()
b) Write a Python program to create a user-defined module and import it in
another file.
Ans)
my_module.py (Create this file)
Python
def greet(name):
print("Hello,", name)
def add(a, b):
return a + b
main.py (Create this file in the same directory)
Python
import my_module
my_module.greet("Alice")
result = my_module.add(5, 3)
print("Sum:", result)
#Or you can import specific functions
#from my_module import greet, add
#greet("Bob")
#print(add(10,2))
c) Explain try-except block in Python with a relevant example.
Ans)
The try-except block is used for handling exceptions (errors) in Python. The
code that might raise an exception is placed inside the try block, and the code
that handles the exception is placed inside the except block.
Example:
Python
try:
num1 = int(input("Enter numerator: "))
num2 = int(input("Enter denominator: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero")
except ValueError:
print("Error: Invalid input. Please enter numbers only.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
Q6. Attempt any TWO of the following: (12 Marks)
a) Explain the NumPy and Pandas packages with examples.
Ans)
NumPy: NumPy (Numerical Python) is a library for numerical computing in
Python. It provides support for large, multi-dimensional arrays and matrices,
along with mathematical functions to operate on these arrays.
Python
import numpy as np
# Creating a NumPy array
arr = np.array([1, 2, 3, 4, 5])
# Performing operations
print(arr + 2) # Adds 2 to each element
print(np.sin(arr))
Pandas: Pandas is a library for data manipulation and analysis. It provides data
structures like DataFrames (tabular data) and Series (one-dimensional data)
that make it easy to work with structured data.
Python
import pandas as pd
# Creating a Pandas DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 28]}
df = pd.DataFrame(data)
# Analyzing data
print(df['Age'].mean())
print(df.sort_values(by='Age'))
b) Write a Python program to generate 5 random integers between 10 and 50
using NumPy.
Ans)
Python
import numpy as np
random_integers = np.random.randint(10, 51, 5) # 51 is exclusive
print(random_integers)
c) Explain any four built-in functions of set with examples.
Ans)
add(): Adds an element to the set.
Python
my_set = {1, 2, 3}
my_set.add(4) # my_set is now {1, 2, 3, 4}
remove(): Removes an element from the set. Raises a KeyError if the element is
not found.
Python
my_set = {1, 2, 3}
my_set.remove(2) # my_set is now {1, 3}
#my_set.remove(5) # Raises KeyError
discard(): Removes an element from the set if