Skip to main content

Chapter 3

Programming with Python

TU BIM past exam questions

Past questions and answers

22 questions set from this chapter. Most repeated first.

  • 2024 AD Model · 1 mark

What is virtual environment?

Answer

A virtual environment is an isolated Python environment with its own interpreter and installed packages, so each project can have its own dependency versions without conflicting with others. It is created with python -m venv myenv and activated with myenv\Scripts\activate (Windows) or source myenv/bin/activate (Linux/macOS).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 AD Model · 1 mark

What are the uses of pass statement?

Answer

pass is a null statement that does nothing. It is used as a placeholder where a statement is syntactically required but no code is ready yet, for example in empty functions, classes, loops, or if/except blocks:

def todo():
    pass

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 AD Model · 1 mark

What is tuple data type?

Answer

A tuple is an ordered, immutable collection of items written in parentheses, e.g. t = (1, "a", 3.5). It allows duplicates and mixed types, supports indexing and slicing, but its elements cannot be changed after creation.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 AD Model · 1 mark

What is frozenset data type?

Answer

A frozenset is an immutable version of a set, created with frozenset([1, 2, 3]). It holds unordered unique elements that cannot be added or removed after creation, so it is hashable and can be used as a dictionary key or as an element of another set.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 AD Model · 1 mark

Define lambda function.

Answer

A lambda function is a small anonymous function defined with the lambda keyword in a single expression: lambda arguments: expression. Example: square = lambda x: x * x, so square(5) gives 25. It is often used with map(), filter() and sorted().

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 AD Model · 1 mark

What is abstract class?

Answer

An abstract class is a class that cannot be instantiated and is meant to be a base for subclasses. It contains one or more abstract methods (declared but without implementation) that subclasses must override. In Python it is created by inheriting from ABC (module abc) and decorating methods with @abstractmethod.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 AD Model · 1 mark

What are the uses of with statement?

Answer

The with statement manages resources using a context manager. It guarantees that set-up and clean-up (such as closing a file or releasing a lock) happen automatically, even if an exception occurs, and makes code shorter and safer:

with open("data.txt") as f:
    text = f.read()

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 AD Model · 1 mark

Define array broadcasting.

Answer

Broadcasting is NumPy's mechanism for performing arithmetic on arrays of different shapes by automatically stretching the smaller array to match the larger one without copying data. For example, np.array([1, 2, 3]) + 10 gives [11, 12, 13], and a (3,3) array can be added to a (3,) array row-wise.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 AD Model · 1 mark

What is data frame in pandas library?

Answer

A DataFrame is the main pandas data structure: a two-dimensional, size-mutable, labelled table with rows and columns, where each column can have a different data type (like a spreadsheet or SQL table). Example: pd.DataFrame({"name": ["Ram", "Sita"], "age": [20, 22]}).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 AD Model · 1 mark

List any four python web development frameworks.

Answer

  1. Django
  2. Flask
  3. FastAPI
  4. Pyramid (others: Bottle, Tornado, CherryPy)

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 AD Model · 3 marks

Explain membership operators with example.

Answer

Membership operators test whether a value is present in a sequence such as a string, list, tuple, set or dictionary (keys). They return a Boolean.

  • in: True if the value is found in the sequence.
  • not in: True if the value is not found in the sequence.
fruits = ["apple", "banana", "mango"]
print("apple" in fruits)        # True
print("grape" not in fruits)    # True
print("an" in "banana")         # True
d = {"a": 1, "b": 2}
print("a" in d)                 # True (checks keys)

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 AD Model · 3 marks

Write a program to count number of vowels in a string.

Answer

s = input("Enter a string: ")
count = 0
for ch in s.lower():
    if ch in "aeiou":
        count += 1
print("Number of vowels:", count)

For input Education, the output is Number of vowels: 5 (E, u, a, i, o).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 AD Model · 3 marks

Compare for loop with while loop. What is bread statement?

Answer

for loopwhile loop
Iterates over a sequence (list, string, range)Repeats while a condition is true
Used when the number of iterations is knownUsed when the number of iterations is unknown
Loop variable is updated automaticallyCounter must be updated manually
Less risk of infinite loopCan become infinite if the condition never turns false
for i in range(3): print(i)
i = 0
while i < 3:
    print(i); i += 1

break statement: break terminates the nearest enclosing loop immediately and transfers control to the statement after the loop.

for n in range(10):
    if n == 5:
        break
    print(n)     # prints 0 to 4

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 AD Model · 3 marks

What is dictionary data type? Why do we need this data type?

Answer

A dictionary is a mutable, unordered-by-key (insertion-ordered since Python 3.7) collection of key: value pairs written in curly braces. Keys must be unique and immutable; values can be of any type.

student = {"name": "Ram", "age": 20}
print(student["name"])     # Ram
student["grade"] = "A"     # add new pair

Why we need it

  • Fast lookup of values by key (average O(1) using hashing).
  • Represents real-world records naturally (name -> value), which is clearer than remembering list indexes.
  • Flexible: easy to add, update and delete items, and values may be lists or other dictionaries (useful for JSON-like data).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 AD Model · 3 marks

Write a program using function to find sum of any numbers passed to the function.

Answer

Using *args, the function accepts any number of arguments:

def total(*numbers):
    s = 0
    for n in numbers:
        s += n
    return s

print(total(5, 10, 15))        # 30
print(total(1, 2, 3, 4, 5))    # 15

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 AD Model · 3 marks

How do you draw multiple plots in a single figure using matplotlib?

Answer

In matplotlib, multiple plots can be put in a single figure using plt.subplot() or plt.subplots(), which divide the figure into a grid of axes.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
fig, ax = plt.subplots(1, 2, figsize=(8, 3))   # 1 row, 2 columns
ax[0].plot(x, np.sin(x)); ax[0].set_title("Sine")
ax[1].plot(x, np.cos(x)); ax[1].set_title("Cosine")
plt.tight_layout()
plt.show()

Equivalently, plt.subplot(1, 2, 1) selects the first plot and plt.subplot(1, 2, 2) the second (rows, columns, index). Several lines can also be drawn on the same axes by calling plt.plot() repeatedly before plt.show().

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 AD Model · 5 marks

Write a program to check a number entered is prime or not.

Answer

n = int(input("Enter a number: "))

if n < 2:
    print(n, "is not prime")
else:
    is_prime = True
    i = 2
    while i * i <= n:
        if n % i == 0:
            is_prime = False
            break
        i += 1
    if is_prime:
        print(n, "is prime")
    else:
        print(n, "is not prime")

A number is prime if it is greater than 1 and has no divisor other than 1 and itself. Checking divisors up to n\sqrt{n} is enough. For n = 29 the loop tests 2, 3, 4, 5 and finds no divisor, so the output is 29 is prime; for n = 21 it finds 3 and prints 21 is not prime.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 AD Model · 5 marks

Explain match-case statement with suitable example.

Answer

match-case (structural pattern matching, Python 3.10+) compares a value against several patterns and runs the block of the first matching case. It works like a switch statement but is more powerful (it can match literals, sequences, dictionaries, classes, and use guards). case _ is the default (wildcard) case.

Syntax:

match expression:
    case pattern1:
        statements
    case pattern2:
        statements
    case _:
        statements

Example:

day = int(input("Enter day number (1-7): "))
match day:
    case 1:
        print("Sunday")
    case 2:
        print("Monday")
    case 3 | 4 | 5 | 6:
        print("Midweek day")
    case 7:
        print("Saturday")
    case _:
        print("Invalid day")

Other patterns:

point = (0, 5)
match point:
    case (0, y):
        print("On y-axis at", y)
    case (x, 0):
        print("On x-axis at", x)
    case (x, y) if x == y:
        print("On diagonal")

Here | combines alternatives, tuple patterns unpack values, and if is a guard. No fall-through occurs, so break is not needed.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 AD Model · 5 marks

Explain list comprehension with example.

Answer

List comprehension is a concise way to create a new list from an iterable in a single line, optionally filtering items.

Syntax: [expression for item in iterable if condition]

Examples:

squares = [x**2 for x in range(1, 6)]              # [1, 4, 9, 16, 25]
evens = [x for x in range(10) if x % 2 == 0]        # [0, 2, 4, 6, 8]
upper = [w.upper() for w in ["ram", "sita"]]        # ['RAM', 'SITA']
pairs = [(a, b) for a in (1, 2) for b in ("x", "y")]

It is equivalent to a longer for loop with append():

squares = []
for x in range(1, 6):
    squares.append(x**2)

Advantages: shorter, more readable and generally faster than the equivalent loop. Similar syntax exists for sets, dictionaries ({k: v for ...}) and generators.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 AD Model · 5 marks

Explain method overriding with suitable example.

Answer

Method overriding occurs when a subclass defines a method with the same name and parameters as a method in its parent class, so the subclass version replaces the parent's version for objects of the subclass. It is the way Python achieves runtime polymorphism. The parent version can still be reached with super().

class Animal:
    def sound(self):
        print("Animal makes a sound")

class Dog(Animal):
    def sound(self):               # overrides Animal.sound
        print("Dog barks")

class Cat(Animal):
    def sound(self):
        super().sound()            # call parent's method
        print("Cat meows")

for a in (Animal(), Dog(), Cat()):
    a.sound()

Output:

Animal makes a sound
Dog barks
Animal makes a sound
Cat meows

The method called depends on the actual object type, not the reference, which allows the same call a.sound() to behave differently for different classes.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 AD Model · 10 marks

Compare class with class. Create a class Rectangle containing instance variables length and breadth. The class also contains two instance methods area() and perimeter() to find area and perimeter of rectangles respectively. Use this class to find area and perimeter of two different rectangles.

Answer

Class vs object

The question's "class with class" reads as "class with object":

ClassObject
Blueprint or template that defines attributes and methodsInstance of a class with actual values
Defined once using the class keywordCreated many times by calling the class
Does not occupy memory for instance data by itselfOccupies memory for its own data
Example: RectangleExample: r1 = Rectangle(5, 3)

Program

class Rectangle:
    def __init__(self, length, breadth):
        self.length = length
        self.breadth = breadth

    def area(self):
        return self.length * self.breadth

    def perimeter(self):
        return 2 * (self.length + self.breadth)

r1 = Rectangle(10, 5)
r2 = Rectangle(7, 3)

print("Rectangle 1: area =", r1.area(), "perimeter =", r1.perimeter())
print("Rectangle 2: area =", r2.area(), "perimeter =", r2.perimeter())

Output

Rectangle 1: area = 50 perimeter = 30
Rectangle 2: area = 21 perimeter = 20

Each object keeps its own length and breadth, so the same methods give different results for different rectangles.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 AD Model · 10 marks

Explain different benefits of relational databases. Assuming your own database and tables, write a program to insert and retrieve data from the database.

Answer

Benefits of relational databases

  1. Structured data: data is stored in tables (rows and columns), simple and easy to understand.
  2. Reduced redundancy: normalisation avoids duplicate data and saves storage.
  3. Data integrity: primary keys, foreign keys and constraints (NOT NULL, UNIQUE, CHECK) keep data accurate and consistent.
  4. Powerful querying: SQL allows flexible retrieval, joins, filtering and aggregation.
  5. ACID transactions: atomicity, consistency, isolation and durability ensure reliable updates.
  6. Security: user privileges and access control.
  7. Multi-user concurrency and scalability, with backup and recovery support.
  8. Data independence: changing storage details does not affect applications.

Program (SQLite, built into Python)

import sqlite3

conn = sqlite3.connect("college.db")
cur = conn.cursor()

cur.execute("""CREATE TABLE IF NOT EXISTS student(
                   id INTEGER PRIMARY KEY,
                   name TEXT NOT NULL,
                   program TEXT)""")

# insert
cur.execute("INSERT INTO student VALUES (?, ?, ?)", (1, "Ram", "BIM"))
cur.executemany("INSERT INTO student VALUES (?, ?, ?)",
                [(2, "Sita", "BBA"), (3, "Hari", "BIM")])
conn.commit()

# retrieve
cur.execute("SELECT * FROM student WHERE program = ?", ("BIM",))
for row in cur.fetchall():
    print(row)

conn.close()

If the script is run a second time, the primary key values would clash; use INSERT OR IGNORE to avoid that. Output of the first run:

(1, 'Ram', 'BIM')
(3, 'Hari', 'BIM')

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

Questions from TU BIM Fifth Semester IT 228 Artificial Intelligence Model Question 2024 (Faculty of Management model question 2024, BIM fifth semester, via EducateNepal), TU BIM Fifth Semester IT 242 Software Design and Development Model Question 2024 (Faculty of Management model question 2024, BIM fifth semester, via EducateNepal), TU BIM Fifth Semester IT 243 Programming with Python Model Question 2024 (Faculty of Management model question 2024, BIM fifth semester, via EducateNepal), TU BIM Fifth Semester IT 244 Information Security Model Question 2024 (Faculty of Management model question 2024, BIM fifth semester, via EducateNepal), TU BIM Fifth Semester MKT 201 Fundamentals of Marketing Model Question 2024 (Faculty of Management model question 2024, BIM fifth semester, via EducateNepal), TU BIM Fifth Semester IT 221 Computer Graphics 2016 (model question) (Faculty of Management model question 2016 (old course), via EducateNepal), TU BIM Fifth Semester IT 222 Java Programming II 2016 (model question) (Faculty of Management model question 2016 (old course), via EducateNepal) and TU BIM Fifth Semester IT 223 Advance Internetworking 2016 (model question) (Faculty of Management model question 2016 (old course), via EducateNepal). Answers are written for this site; check them against your class notes.