Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. BIM 5th Sem-Exam Question Solution 2025 – Python

BIM 5th Sem-Exam Question Solution 2025 – Python

BIM 5th Sem-Exam Question Solution 2025 – Python

Thank you for reading this post, don't forget to subscribe!

1.) What is the output of print(3 ** 3) / (3**2)?

3 ** 3 = 27, 3 ** 2 = 9. So the result is print(27 / 9) which is 3.0.

2.) What happens when the pass statement is executed?

The pass statement does nothing and acts as a placeholder. It is used when a statement is syntactically required but no action is needed.

3.) Define escape sequence.

An escape sequence is a combination of characters starting with a backslash () that represents special characters in a string, like \n for a newline or \t for a tab.

4.) Define lambda function.

A lambda function is a small, anonymous function defined using the lambda keyword, typically used for short, one-line operations, e.g., lambda x: x + 1.

5.) How do you check if a key exists in a dictionary?

The in operator checks whether the specified key exists in the dictionary.. Example: if “name” in my_dict: checks if “name” exists as a key.

6.) Why do we need abstract class?

An abstract class provides a blueprint for other classes, ensuring they implement specific methods, and cannot be instantiated directly.

7.) How can you convert a string to a list in Python?

Use the list() function. Example: list(“hello”) returns [‘h’, ‘e’, ‘l’, ‘l’, ‘o’].

8.) What is the task of static method?

A static method is used to define functionality that belongs to the class but does not operate on instance variables.

9.) What is tuple data type?

A tuple is an immutable, ordered collection of elements, defined using parentheses, e.g., (1, 2, 3).

10.) How do you return multiple values in function?

In Python, a function can return multiple values by separating them with commas. Internally, these values are returned as a tuple

11.) What is the purpose of the try-except block in Python? Give an example.

The try-except block in Python is used to catch and handle exceptions (runtime errors) that may arise during the execution of code, ensuring that the program can continue running or fail gracefully with a helpful message.

Example:

try:
    x = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

12.) Create a program that counts the number of vowels in a given string.

text = "hello world"
vowels = "aeiouAEIOU"
count = 0
for char in text:
    if char in vowels:
        count += 1
print("Number of vowels:", count)

13.) Describe the importance of DataFrame.

A DataFrame is a powerful data structure provided by the Pandas library in Python, used for storing and manipulating tabular data—much like a table in a database or an Excel spreadsheet.

  • Tabular Data Structure: It organizes data in rows and columns, making it easy to read and manipulate.
  • Handles Heterogeneous Data: It can store different data types (e.g., integers, strings, floats) in different columns.
  • Powerful Data Manipulation: It offers built-in functions for filtering, sorting, grouping, merging, reshaping, and more.
  • Data Cleaning: It provides tools for handling missing or inconsistent data efficiently.
  • Performance: It supports vectorized operations, which are faster and more efficient than traditional loops.

14.) Create a NumPy array of 10 random integers.

import numpy as np
arr = np.random.randint(1, 100, size=10)
print(arr)
  • import numpy as np: Imports the NumPy library.
  • np.random.randint(1, 101, size=10): Generates 10 random integers from 1 to 100 (inclusive of 1, exclusive of 101).
  • print(…): Displays the array.

15.) How do you create and call the function?

In Python, a function is defined using the def keyword followed by the function name and parentheses. A function is called by writing its name followed by parentheses.

def greet():
    print("Hello, World!")

greet()

16.) Create a program that converts a list of integers to a set.

my_list = [1, 2, 2, 3, 4]
my_set = set(my_list)
print(my_set)
  • A list can have duplicate values.
  • A set stores only unique elements.
  • Using set() converts the list into a set, removing any duplicate integers.

17.) Write a program to read a string as input and write it to the file.

text = input("Enter a string: ")
with open("output.txt", "w") as f:
    f.write(text)
print("Data written to output.txt")
  • input() takes input from the user as a string.
  • open(“output.txt”, “w”) opens the file named output.txt in write mode. If the file does not exist, it will create one.
  • The with statement ensures the file is properly closed after writing.
  • file.write() writes the string to the file.
  • Finally, the program confirms the string has been written.

18.) How do you draw bar chart and pie chart? Illustrate with example.

import matplotlib.pyplot as plt

labels = ['A', 'B', 'C']
values = [20, 30, 50]

# Bar Chart
plt.bar(labels, values)
plt.title("Bar Chart")
plt.show()

# Pie Chart
plt.pie(values, labels=labels, autopct="%1.1f%%")
plt.title("Pie Chart")
plt.show()

19.) List and explain any five built-in data types.

  • int: It represents integer values (whole numbers without decimal points).. Example: x = 10
  • float: It represents decimal (floating-point) numbers. Used for numbers with fractions. Example: y = 3.14
  • str: It represents a sequence of characters, used for storing text. Strings are enclosed in quotes.. Example: name = “Alice”
  • list: It is an ordered and mutable collection of items. Items can be of different types and lists can be modified (items added, removed, changed). Example: nums = [1, 2, 3]
  • dict: It is a collection of key-value pairs. Each key is unique and used to access its corresponding value. Example: d = {“id”: 1, “name”: “Bob”}

20.) Create a list of ten random numbers and sort it.

import random
numbers = random.sample(range(1, 100), 10)
print("Original:", numbers)
numbers.sort()
print("Sorted:", numbers)

This code uses the random module to generate random integers, stores them in a list, then sorts the list using the sort() method.

21.) Consider a database named college with table student(id, name, address, phone, semester, faculty). Write a program to insert any five records and retrieve the name and address of students who studied in fifth semester.

import sqlite3

# Step 1: Connect to database (creates college.db if it doesn't exist)
conn = sqlite3.connect("college.db")
cursor = conn.cursor()

# Step 2: Create the student table
cursor.execute("""
CREATE TABLE IF NOT EXISTS student (
    id INTEGER PRIMARY KEY,
    name TEXT,
    address TEXT,
    phone TEXT,
    semester INTEGER,
    faculty TEXT
)
""")

# Step 3: Insert five records into the student table
students = [
    (1, "Alice", "Kathmandu", "9841000001", 5, "BIM"),
    (2, "Bob", "Lalitpur", "9841000002", 4, "BIM"),
    (3, "Charlie", "Bhaktapur", "9841000003", 5, "BBA"),
    (4, "David", "Pokhara", "9841000004", 6, "BIM"),
    (5, "Eve", "Butwal", "9841000005", 5, "BCA")
]

cursor.executemany("INSERT INTO student VALUES (?, ?, ?, ?, ?, ?)", students)

# Step 4: Commit the changes
conn.commit()

# Step 5: Retrieve name and address of students in 5th semester
cursor.execute("SELECT name, address FROM student WHERE semester = 5")
results = cursor.fetchall()

# Step 6: Print the results
print("Students in 5th Semester:")
for name, address in results:
    print("Name:", name, "| Address:", address)

# Step 7: Close the connection
conn.close()
#output

Students in 5th Semester:
Name: Alice, Address: Kathmandu
Name: Charlie, Address: Bhaktapur
Name: Eve, Address: Butwal

22.) What are the limitation of operator overloading? Write a program to create a class vehicle with attribute speed. Create a subclass car and truck that inherits from vehicles and adds an attribute fuel-type. Then create another sub class EV car that inherits from car and add a method charge-battery().

Operator overloading allows developers to redefine the meaning of built-in operators (like +, -, *) for user-defined classes.

Limitations:

  • Confusion and Misuse: It can make the code harder to understand if not used properly. Overloading an operator to perform unrelated tasks reduces code readability.
  • Limited Set of Overloadable Operators: Some operators like = (assignment) or . (dot operator) cannot be overloaded.
  • Inconsistency: Improper overloading may result in behavior that differs from expected operator behavior, which can cause bugs.
  • Performance Overhead: Custom implementation of operators might be slower than the built-in versions.

Program:

# Base class
class Vehicle:
    def __init__(self, speed):
        self.speed = speed

# Subclass Car
class Car(Vehicle):
    def __init__(self, speed, fuel_type):
        super().__init__(speed)
        self.fuel_type = fuel_type

# Subclass Truck
class Truck(Vehicle):
    def __init__(self, speed, fuel_type):
        super().__init__(speed)
        self.fuel_type = fuel_type

# Subclass EVCar (Electric Car) inheriting from Car
class EVCar(Car):
    def __init__(self, speed):
        super().__init__(speed, fuel_type="Electric")

    def charge_battery(self):
        print("Charging battery...")

# Example Usage
ev = EVCar(120)
print(f"EV Car Speed: {ev.speed} km/h")
print(f"Fuel Type: {ev.fuel_type}")
ev.charge_battery()

Output:

EV Car Speed: 120 km/h
Fuel Type: Electric
Charging battery...

How can we help?