Programming with Python

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

BIM 5th Sem-Model Question Solution 2024 – Python

BIM 5th Sem-Model Question Solution 2024 – Python

1.) What is virtual environment?

A Virtual Environment in Python is an isolated workspace where you can install dependencies separately from the global Python installation.

2.) What are the uses of pass statement?

The pass statement is used as a placeholder in Python when a statement is syntactically required but no action is needed.

3.) What is tuple data type?

A tuple in Python is an ordered, immutable collection of items, enclosed in parentheses ( ). Like lists, tuples can store elements of different data types, but unlike lists, tuples cannot be changed after creation.

4.) What is frozenset data type?

A frozenset is an immutable version of a set. Once created, its elements cannot be changed, i.e., you can’t add or remove items.

5.) Define lambda function.

A lambda function in Python is a small anonymous function defined using the lambda keyword.

  • It is used to create quick, single-expression functions without needing to formally define them using def.

6.) What is abstract class?

An abstract class in Python is a class that cannot be instantiated directly and is used as a blueprint for other classes.

7.) What are the uses of with statement?

The with statement in Python is used to wrap the execution of a block with methods defined by a context manager.

  • It simplifies resource management such as opening and closing files, and ensures that resources are properly released, even if an error occurs within the block.

8.) Define array broadcasting.

Array broadcasting in NumPy refers to the ability to perform arithmetic operations on arrays of different shapes and sizes.

9.) What is data frame in pandas library?

A DataFrame in the pandas library is a two-dimensional, tabular data structure with labeled axes (rows and columns).

  • It is similar to a spreadsheet or SQL table and allows for efficient data manipulation, analysis, and visualization.

10.) List any four python web development frameworks.

Any four Python web development frameworks:

  • Flask
  • Django
  • FastAPI
  • Pyramid

11.) Explain membership operators with example.

Membership operators in Python are used to test whether a value or variable is present in or not present in a sequence such as a string, list, tuple, set, or dictionary.

Python provides two membership operators:

  • in – Returns True if the value is found in the sequence.
  • not in – Returns True if the value is not found in the sequence.

Examples:

# Using 'in'
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits)       # Output: True

# Using 'not in'
print("grape" not in fruits)   # Output: True

# Membership in string
message = "Hello, Python!"
print("Python" in message)     # Output: True

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

# Program to count number of vowels in a string 

vowels = "aeiouAEIOU"
count = 0

# Input from user
text = input("Enter a string: ")

# Loop through each character in the string
for char in text:
    if char in vowels:
        count += 1

# Display the result
print("Number of vowels:", count)

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

for Loopwhile Loop
A for loop is used to iterate over a sequence like a list, string, or range.A while loop repeats a block of code as long as a specified condition is true.
Used when the number of iterations is known or predetermined.Used when the number of iterations is not known in advance.
Example: for i in range(5): print(i)Example: i = 0; while i < 5: print(i); i += 1
Less prone to infinite loops.More prone to infinite loops if the condition is not properly handled.

The break statement is used to exit a loop prematurely, stopping the execution of the loop. It stops the execution of the loop or switch and transfers control to the next statement outside of the loop.

14.) What is dictionary data type? Why do we need this data type?

A dictionary in Python is a collection of key-value pairs. It allows fast access to data by keys, not by index.

  • They are unordered and mutable, meaning you can add, update, or delete key-value pairs.
  • it is defined using curly braces {} with colon : separating keys and values.

Dictionaries are useful in programming for several reasons:

  • Efficient Data Retrieval:
    • Dictionaries allow fast retrieval of values using keys. This is faster compared to lists when accessing an element based on a specific identifier.
  • Mapping Relationships:
    • You can map one piece of data (the key) to another (the value). For example, mapping student IDs to names, or storing employee details using their employee IDs.
  • Flexibility:
    • Dictionaries can store values of any data type, including other dictionaries, lists, or functions, which makes them versatile in many scenarios.
  • Unordered Data:
    • Dictionaries are unordered, but the key-value pairs can be accessed using the key directly, making them useful for situations where order doesn’t matter, but quick access to data does.
  • Mutability:
    • Unlike tuples, dictionaries can be modified (values updated, new keys added, or key-value pairs removed), which makes them adaptable for many dynamic operations.

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

# Function to calculate sum
def find_sum(a, b):
    return a + b

# Example of calling the function
result = find_sum(5, 10)
print("The sum is:", result)
  • The find_sum function takes two numbers a and b and returns their sum.
  • We call the function with two numbers, 5 and 10, and the result is printed.

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

In Matplotlib, you can draw multiple plots in a single figure using the subplot() function or plt.subplots().

  • These allow you to create multiple subplots in a single figure, enabling you to visualize different graphs together.

Method 1: Using subplot():
subplot() divides the figure into a grid and places the plots in different positions.

import matplotlib.pyplot as plt

# First subplot
plt.subplot(2, 1, 1)  # 2 rows, 1 column, 1st plot
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], label="Line 1")
plt.title("Plot 1")

# Second subplot
plt.subplot(2, 1, 2)  # 2 rows, 1 column, 2nd plot
plt.plot([1, 2, 3, 4], [16, 9, 4, 1], label="Line 2", color="red")
plt.title("Plot 2")

# Display both plots
plt.tight_layout()  # Automatically adjust layout to avoid overlap
plt.show()

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

# Taking user input
num = int(input("Enter a number: "))

# Function to check if the number is prime
if num > 1:
    for i in range(2, num):
        if num % i == 0:
            print(f"{num} is not a prime number.")
            break
    else:
        print(f"{num} is a prime number.")
else:
    print(f"{num} is not a prime number.")
  • The program prompts the user to enter a number.
  • If the number is greater than 1, it checks if it is divisible by any number between 2 and the number minus 1.
  • If the number is divisible by any of these, it is not prime, and the program prints “not a prime number.”
  • If it is not divisible by any number in the range, it is prime, and the program prints “prime number.”
  • The else block after the for loop ensures that if no divisors are found, the number is declared prime.

18.) Explain match-case statement with suitable example.

The match-case statement is a pattern-matching feature introduced in Python 3.10. It allows for cleaner and more readable code for scenarios where multiple conditions need to be checked, similar to a switch statement in other languages.

Syntax:

match variable:
    case pattern1:
        # Code to execute if variable matches pattern1
    case pattern2:
        # Code to execute if variable matches pattern2
    case _:
        # Code to execute if no patterns match (default case)
day = int(input("Enter a day number (1-7): "))
match day:
    case 1:
        print("Monday")
    case 2:
        print("Tuesday")
    case 3:
        print("Wednesday")
    case 4:
        print("Thursday")
    case 5:
        print("Friday")
    case 6:
        print("Saturday")
    case 7:
        print("Sunday")
    case _:
        print("Invalid day number.")

19.) Explain list comprehension with example.

List comprehension is a concise way to create lists in Python. It provides a shorter and more readable syntax to generate a new list by performing an operation on each element of an existing iterable (like a list, range, etc.).

Syntax:

[expression for item in iterable if condition]
  • expression: The value to include in the new list.
  • item: The current element in the iteration.
  • iterable: A sequence like a list, tuple, or range.
  • condition (optional): A filter that selects which items to include.

Example: Get even numbers from a list

numbers = [1, 2, 3, 4, 5, 6]
even = [x for x in numbers if x % 2 == 0]
print(even)

#output: [2, 4, 6]

20.) Explain method overriding with suitable example.

Method Overriding occurs in object-oriented programming when a subclass (child class) provides a specific implementation of a method that is already defined in its superclass (parent class).

  • The overridden method in the child class has the same name, same parameters, and same return type as the method in the parent class.
  • It allows polymorphism – the same method name behaves differently based on the object.
  • The method in the child class overrides the one in the parent class.
class Animal:
    def speak(self):
        print("Animal makes a sound")

class Dog(Animal):
    def speak(self):
        print("Dog barks")

# Create objects
a = Animal()
d = Dog()

# Call the speak method
a.speak()  # Output: Animal makes a sound
d.speak()  # Output: Dog barks
  • Animal has a method speak().
  • Dog, which inherits from Animal, overrides the speak() method with its own version.
  • When speak() is called on a Dog object, the child class’s method runs, not the parent’s.

21.) 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.

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)

# Create two rectangle objects
rect1 = Rectangle(10, 5)
rect2 = Rectangle(7, 3)

# Find and display area and perimeter of both rectangles
print("Rectangle 1:")
print("Area:", rect1.area())
print("Perimeter:", rect1.perimeter())

print("\nRectangle 2:")
print("Area:", rect2.area())
print("Perimeter:", rect2.perimeter())
#output:
Rectangle 1:
Area: 50
Perimeter: 30

Rectangle 2:
Area: 21
Perimeter: 20

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

A relational database is a type of database that stores data in a structured format using tables. Each table, also known as a relation, consists of rows (records) and columns (fields).

  • The data in different tables can be linked using relationships, usually by employing primary keys and foreign keys.

Relational databases (RDBMS) like MySQL, SQLite, and PostgreSQL store data in structured formats using tables. Each table has rows and columns, and relationships can be created among tables using keys.

Here are key benefits:

  • Data Integrity: It maintains accuracy through constraints like primary keys, foreign keys, and unique constraints.
  • Flexibility: In relational database, data can be updated, inserted, or deleted without affecting application structure.
  • Query Capability: It allows powerful queries using SQL (Structured Query Language) for filtering, joining, and aggregating data.
  • Security: It supports access control and authorization to ensure data protection.
  • Relationships: In relational database, tables can be related using primary and foreign keys, reducing data redundancy.
  • Scalability and Maintenance: It is easy to scale and maintain data due to its structured nature.

Python Program Using sqlite3
Assume a student database with a table called students having id, name, and marks.

Code to Insert and Retrieve Data:

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 data 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

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *