Q.1 a) What are the types of problems?
Answer: Conceptual homework problem
Problems can be broadly categorized into several types, often depending on the field or
context. Common categorizations include:
Algorithmic Problems: Problems that can be solved using a defined sequence of steps or an
algorithm.
Heuristic Problems: Problems that require a discovery process using general rules of thumb,
as a guaranteed solution method is not known.
Open Problems: Unsolved problems in a field of study.
Decision Problems: Problems with a yes/no answer.
Optimization Problems: Problems that aim to find the best possible solution among a set of
alternatives.
Conceptual Problems: Problems that test understanding of a concept or definition.
Procedural Problems: Problems that require following a set of steps or calculations to reach
a solution.
Q.1 b) Explain brief history of python programming language and list different software
developed in python.
Answer: Conceptual homework problem
History of Python: Python was created by Guido van Rossum in the late 1980s and early
1990s at CWI in the Netherlands. It was conceived as a successor to the ABC programming
language, capable of exception handling and interfacing with the Amoeba operating
system. Van Rossum is Python's "Benevolent Dictator For Life" (BDFL), meaning he oversees
the Python development process. Python 2.0 was released in 2000, and Python 3.0 (which
was a major revision and not backward compatible) was released in 2008.
Software Developed in Python: Many popular applications and frameworks are built using
Python, including:
Instagram: The popular social media platform uses Python on its backend servers.
Spotify: Uses Python for many of its backend services and data analysis.
Netflix: Extensively uses Python for various services, including security, recommendation
engines, and data analysis.
Dropbox: The file hosting service's desktop client and much of its backend logic are written
in Python.
Google: Uses Python for many internal systems and services.
YouTube: Uses Python as a core language for its platform.
Q.1 c) Describe object oriented programming features.
Answer: Conceptual homework problem
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of
"objects", which can contain data (attributes) and code (methods). Key features include:
Encapsulation: The bundling of data and the methods that operate on that data into a single
unit (an object). This hides the internal state of the object from the outside world.
Inheritance: A mechanism where a new class (subclass/derived class) derives properties and
behavior (attributes and methods) from an existing class (superclass/base class). This
promotes code reuse.
Polymorphism: The ability of different objects to respond to the same message or method
call in different ways. It allows a single interface to be used for general actions.
Abstraction: The concept of hiding complex implementation details and showing only the
necessary features of an object. It focuses on what the object does rather than how it does
it.
Q.1 d) Define problem solving. Write down steps of problem solving process.
Answer: Conceptual homework problem
Definition of Problem Solving: Problem solving is the process of identifying a problem,
developing a plan, executing the plan, and evaluating the results to find a satisfactory
solution. In a computing context, it involves defining the problem and then creating an
algorithm or program to solve it.
Steps of Problem Solving Process: A common sequence of steps includes:
Problem Definition/Identification: Clearly understanding and stating the problem.
Analysis: Breaking the problem down into smaller, manageable parts and identifying
constraints.
Algorithm Development: Designing a step-by-step procedure (algorithm) to solve the
problem.
Coding/Implementation: Translating the algorithm into a specific programming language
code.
Testing and Debugging: Running the program to ensure it works correctly and fixing any
errors (bugs).
Maintenance: Updating and improving the program over time as needed.
Q.2 a) Describe flowchart and symbols in detail.
Answer: Conceptual homework problem
A flowchart is a diagram that illustrates the sequence of operations to be performed to get
the solution of a problem. Common symbols include:
Oval (Terminator): Represents the start or end point of a process.
Rectangle (Process): Represents a single step or operation in the process.
Diamond (Decision): Indicates a point where a decision must be made, typically a yes/no
question, with different paths for each outcome.
Parallelogram (Input/Output): Represents the inputting of data or the outputting of results.
Arrows (Flowlines): Show the direction of the flow of control from one symbol to another.
Cylinder (Database/Storage): Represents data storage.
Q.2 b) Write down the applications of python programming languages.
Answer: Conceptual homework problem
Python is a versatile language with a wide range of applications:
Web Development: Used in backend development with frameworks like Django and Flask.
Data Science & Machine Learning: Widely used for data analysis, visualization, and building
ML models with libraries like NumPy, Pandas, Scikit-learn, and TensorFlow.
Artificial Intelligence: A primary language for AI development.
Automation & Scripting: Used for writing scripts to automate repetitive tasks.
Software Testing: Used for test automation.
Scientific & Numeric Computing: Used in academic and research fields.
Q.2 c) Explain the python programming features.
Answer: Conceptual homework problem
Key features of the Python programming language include:
Easy to Learn and Use: Python has a simple, clean syntax that resembles plain English,
making it beginner-friendly.
Interpreted Language: Python code is executed line by line by an interpreter, which makes
debugging easier.
Dynamically Typed: Variable types are determined at runtime, so there is no need to declare
variable types explicitly.
Object-Oriented: Python supports all OOP concepts like encapsulation, inheritance, and
polymorphism.
Extensive Standard Library: Python comes with a vast collection of built-in modules and
libraries that provide functionality for various tasks.
Portable: Python code can run on various platforms (Windows, macOS, Linux) without
modification.
Q.2 d) Describe TOP-DOWN design approach in detail.
Answer: Conceptual homework problem
The Top-Down design approach (also known as step-wise refinement or modular
programming) is a method for breaking down a large, complex problem into smaller, more
manageable sub-problems or modules.
The process starts with the main goal or overall problem at the highest level.
This main problem is then divided into several high-level functions or tasks.
Each of these sub-problems is further broken down into even smaller, more detailed sub-
problems or procedures.
This hierarchical decomposition continues until each sub-problem is simple enough to be
solved easily, often with a short piece of code or a single function.
The individual modules are developed and tested independently, and then integrated to
form the complete solution. This approach improves readability, maintainability, and
reusability of code.
Q.3 a) List down all the advanced data types in python & Explain any two.
Answer: Conceptual homework problem
Python's built-in advanced data types include:
Lists: Ordered, mutable collections of items.
Tuples: Ordered, immutable collections of items.
Dictionaries: Unordered collections of key-value pairs.
Sets: Unordered collections of unique items.
Explanation of two:
Lists: Lists are used to store multiple items in a single variable. They are created using square
brackets []. Items in a list can be modified, added, or removed after creation.
Example: my_list = [1, "hello", 3.14]
Dictionaries: Dictionaries store data in key-value pairs. They are created using curly
braces {}. Keys must be unique and immutable, while values can be of any data type. They
are highly optimized for retrieving values when the key is known.
Example: my_dict = {"name": "Alice", "age": 30}
Q.3 b) Describe the following terms with examples: i) range ii) break iii) continue iv) pass v)
string
Answer: Conceptual homework problem
i) range(): A built-in function that generates a sequence of numbers. It is often used for
iterating in for loops.
Example: for i in range(3): print(i) outputs 0, 1, 2.
ii) break: A statement used to terminate the current loop prematurely and transfer execution
to the statement immediately following the loop.
Example: for i in range(5): if i == 3: break; print(i) outputs 0, 1, 2.
iii) continue: A statement used to skip the rest of the current iteration of a loop and continue
with the next iteration.
Example: for i in range(5): if i == 3: continue; print(i) outputs 0, 1, 2, 4.
iv) pass: A null operation; nothing happens when it executes. It is used as a placeholder
where a statement is syntactically required but no action is needed.
Example: if True: pass
v) string: A sequence of characters used to store text data. Strings are immutable in Python.
Example: my_string = "Python is great"
Q.3 c) Implement a python program to check whether a number entered by user is even or
odd.
Program to check if a number is even or odd
Step 1: Get input from the user and convert to integer
num = int(input("Enter a number: "))
Step 2: Check if the number is divisible by 2 using the modulo operator
if (num % 2) == 0:
Step 3: Print the appropriate message based on the condition
print(f"{num} is an even number")
else:
print(f"{num} is an odd number")
Answer:
The program will take an integer input from the user and determine if it is even or odd using
the modulo operator.
Q.3 d) Explain conditional control statement in python in detail.
Answer: Conceptual homework problem
Conditional control statements in Python allow the program to make decisions and execute
different code blocks based on whether a condition is true or false. The primary statements
are if, elif (else if), and else.
if statement: Executes a block of code if the condition is true.
Example: if x > 0: print("Positive")
else statement: Executes a block of code if the condition in the preceding if statement is
false.
Example: if x > 0: print("Positive") else: print("Not positive")
elif statement: Allows checking multiple conditions sequentially. If the if condition is false, it
checks the elif condition, and so on.
Example: if x > 0: print("Positive") elif x < 0: print("Negative") else: print("Zero")
Q.4 a) Explain all arithmetic operators with suitable example.
Answer: Conceptual homework problem
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication, and division.
Addition (+): Adds two operands. Example: 5 + 3 results in 8.
Subtraction (-): Subtracts the right operand from the left. Example: 5 - 3 results in 2.
Multiplication (*): Multiplies two operands. Example: 5 * 3 results in 15.
Division (/): Divides the left operand by the right and returns a float. Example: 5 / 3 results in
approximately 1.666.
Floor Division (//): Divides the left operand by the right and returns the integer part of the
result. Example: 5 // 3 results in 1.
Modulo (%): Returns the remainder of the division. Example: 5 % 3 results in 2.
Exponentiation (**): Raises the left operand to the power of the right. Example: 5 **
3 results in 125.
Q.4 b) Write down the difference between for loop and while loop.
Answer: Conceptual homework problem
Feature For Loop While Loop
Usage Iterates over a sequence (list, tuple, Repeats a block of code as long as a given
string, range) or other iterable objects. condition is true.
Control Number of iterations is usually known Number of iterations is not necessarily
beforehand (determined by the known in advance (depends on when the
sequence length). condition becomes false).
Syntax for item in sequence: while condition:
Initialization Loop variable is initialized automatically Loop variable must be initialized before the
by the sequence. loop starts.
Q.4 c) Develop a python program to check whether a given number is even or odd.
Program to check if a number is even or odd
Step 1: Get input from the user and convert to integer
num = int(input("Enter a number: "))
Step 2: Check if the number is divisible by 2 using the modulo operator
if (num % 2) == 0:
Step 3: Print the appropriate message based on the condition
print(f"{num} is an even number")
else:
print(f"{num} is an odd number")
Answer:
The program will take an integer input from the user and determine if it is even or odd using
the modulo operator.
Q.4 d) What is the dictionary data type? Explain any 3 operations of the dictionary data type.
Answer: Conceptual homework problem
Dictionary Data Type: A dictionary is an unordered collection of data in Python used to store
data values in key:value pairs. It is a mutable, indexed collection where each key must be
unique and immutable. Dictionaries are optimized for data retrieval.
Operations:
Accessing values: Values are accessed using their corresponding keys. Example: my_dict =
{'a': 1}; value = my_dict['a']
Adding/Modifying elements: New key-value pairs can be added, or existing values modified,
using assignment. Example: my_dict['b'] = 2 or my_dict['a'] = 10
Deleting elements: Items can be removed using the del keyword or methods
like .pop(). Example: del my_dict['a']
Q.5 a) Compare Regular functions and Lambda functions in python with suitable examples.
Answer: Conceptual homework problem
Feature Regular Function Lambda Function
Syntax Defined using def keyword. Defined using lambda keyword.
Structure Can have multiple expressions and statements. Can only have a single expression.
b) Describe the use of the return statement in functions with examples.
Answer: The return statement is used to exit a function and send a value back to the caller.
The return statement immediately terminates the execution of the function it is in and
passes the specified value back to the code that called it. If no value is specified, or if
the return statement is omitted, the function returns None by default.
Example:
Python
def add_numbers(a, b):
# Calculates the sum
sum_val = a + b
# Returns the sum to the caller
return sum_val
result = add_numbers(5, 3)
# The value 8 is assigned to 'result'
print(result)
c) Develop an algorithm/program to concatenate two strings using + operator.
Step 1: Define a function for concatenation
Define a function that accepts two strings as arguments.
Python
def concatenate_strings(str1, str2):
Step 2: Use the '+' operator
Inside the function, use the + operator to combine the two strings.
Python
combined_string = str1 + str2
Step 3: Return the result
Return the newly concatenated string from the function.
Python
return combined_string
Step 4: Call the function and print the result
Outside the function, define two input strings, call the function with these strings, and print
the output.
Python
string1 = "Hello, "
string2 = "World!"
result = concatenate_strings(string1, string2)
print(result)
Answer:
A Python program that concatenates two strings using the + operator:
Python
def concatenate_strings(str1, str2):
combined_string = str1 + str2
return combined_string
string1 = "Hello, "
string2 = "World!"
result = concatenate_strings(string1, string2)
print(result)
6. a) Analyze the difference between ord() and chr() functions with examples.
Answer: ord() converts a character to its Unicode integer value, while chr() converts a
Unicode integer value back to its corresponding character.
ord(c): Takes a string of length one as an argument and returns an integer representing the
Unicode code point of the character.
chr(i): Takes an integer (Unicode value) as an argument and returns the corresponding
character string.
Examples:
Python
# Using ord()
char = 'A'
unicode_value = ord(char)
print(f"The Unicode value of '{char}' is: {unicode_value}") # Output: The Unicode value of 'A'
is: 65
# Using chr()
value = 97
character = chr(value)
print(f"The character for the value {value} is: {character}") # Output: The character for the
value 97 is: a
b) Explain the concepts of variable scope (local and global) and lifetime in python with
suitable code examples.
Answer: Variable scope determines where a variable is accessible in a program, while
lifetime refers to how long a variable exists in memory.
Scope (Local and Global):
Global scope: Variables defined outside any function are global and can be accessed from
anywhere in the program.
Local scope: Variables defined inside a function are local to that function and can only be
accessed within that function.
Lifetime:
The lifetime of a variable is the period during which it resides in memory. Global variables
exist from the moment they are defined until the program terminates. Local variables exist
only while the function they are in is executing; they are destroyed once the function
returns.
Example:
Python
# Global variable
global_var = 20
def my_function():
# Local variable
local_var = 10
print(f"Inside function (local): {local_var}")
print(f"Inside function (global): {global_var}")
my_function()
# local_var cannot be accessed here, it is out of scope and its lifetime ended
print(f"Outside function (global): {global_var}")
c) Implement program to reverse a string using user defined function.
Step 1: Define a function for reversing a string
Define a function that takes a string as input.
Python
def reverse_string(s):
Step 2: Use slicing to reverse the string
Inside the function, use Python's extended slicing [::-1] to reverse the string efficiently.
Python
reversed_s = s[::-1]
Step 3: Return the reversed string
Return the result to the caller.
Python
return reversed_s
Step 4: Get user input and call the function
Prompt the user for input, call the function with the input, and print the result.
Python
user_input = input("Enter a string: ")
result = reverse_string(user_input)
print(f"The reversed string is: {result}")
Answer:
A Python program to reverse a string using a user-defined function:
Python
def reverse_string(s):
reversed_s = s[::-1]
return reversed_s
user_input = input("Enter a string: ")
result = reverse_string(user_input)
print(f"The reversed string is: {result}")
Q7 a) Describe the purpose & use of file handling
Answer: File handling allows programs to interact with files stored on a computer's storage
system.
Explanation:
Purpose: The primary purpose of file handling is to store data permanently. While variables
and data structures in a program are temporary and lost when the program ends, files
provide persistent storage.
Use:
Reading data: Programs can read input from files, which is useful for processing large
datasets or configuration settings.
Writing data: Programs can save output, results, or user data to files for future use or
analysis.
Data persistence: Ensures information remains available across different program
executions.
Q7 b) Differentiate between mutable and immutable data types with focus on dictionaries in
python. Provide examples
Answer: Mutable data types can be modified after creation, while immutable data types
cannot.
Explanation:
Mutable Data Types:
Their state can be changed in place after creation.
Examples include list, dict, and set.
Dictionaries (dict) in Python are mutable. This means you can add, remove, or change key-
value pairs within an existing dictionary object.
Example:
Python
my_dict = {'a': 1}
my_dict['b'] = 2 # Modifying the dictionary
Immutable Data Types:
Their value cannot be changed after they are created. Any operation that seems to modify
them actually creates a new object.
Examples include int, float, str, tuple, and bool.
Example:
Python
my_string = "Hello"
# my_string[0] = 'h' # This would cause an error
my_string = my_string + " World" # Creates a new string object
Q7 c) Implement a program to append data to an already existing file
Append data to file
Step 1: Open the file in append mode
The file is opened using the open() function with the mode 'a'. If the file does not exist, it
will be created.
Python
file_object = open("[Link]", "a")
Step 2: Append data to the file
The write() method is used to add new content to the end of the file.
Python
file_object.write("This is a new line of appended text.\n")
Step 3: Close the file
It is crucial to close the file using the close() method to ensure all data is written and
resources are freed.
Python
file_object.close()
Answer:
Python
# Full program to append data to an already existing file
try:
with open("[Link]", "a") as file_object:
file_object.write("This is a new line of appended text.\n")
print("Data appended successfully.")
except IOError as e:
print(f"An error occurred: {e}")
Q8 a) Explain different types of files in detail
Answer: Files can be broadly categorized into text files and binary files based on how data is
stored and interpreted.
Explanation:
Text Files:
Store data as a sequence of characters encoded using standards like ASCII or Unicode (UTF-
8).
They are human-readable and can be opened and edited using a standard text editor.
Data is stored line by line, often separated by newline characters.
Examples: .txt, .csv, .py, .html.
Binary Files:
Store data in the raw binary format (zeros and ones) that the computer processes directly.
They are not human-readable when opened in a text editor, often appearing as gibberish.
They are typically more efficient for storing complex data structures, images, audio, and
executable code.
Examples: .jpg, .mp3, .exe, .pdf, .docx.
Q8 b) Explain key directory methods: mkdir(), rmdir(), listdir(), and chdir() with syntax and
usage example.
Answer: The os module in Python provides functions to interact with the operating system's
directory structure.
Explanation:
[Link](path):
Syntax: [Link](path, mode=0o777)
Usage: Creates a new directory (folder) at the specified path. It raises an error if the
directory already exists.
Example: [Link]("new_folder")
[Link](path):
Syntax: [Link](path)
Usage: Removes the specified directory. It can only remove empty directories.
Example: [Link]("new_folder")
[Link](path):
Syntax: [Link](path='.')
Usage: Returns a list containing the names of the entries (files and directories) in the
directory given by path. If no path is specified, it uses the current directory (.).
Example: files_and_dirs = [Link](".")
[Link](path):
Syntax: [Link](path)
Usage: Changes the current working directory of the process to the specified path.
Example: [Link]("new_folder")
Q8 c) Develop a program to print the absolute path of a file using [Link]
Print absolute path
Step 1: Import the os module
The os module is required to interact with the operating system paths.
Python
import os
Step 2: Define a relative filename
Specify the name of the file within the current working directory.
Python
filename = "[Link]"
Step 3: Get the absolute path
Use [Link]() to convert the relative path to an absolute
path. The [Link]() function is used to securely join path components.
Python
absolute_path = [Link]([Link]([Link](), filename))
Answer:
Python
# Full program to print the absolute path of a file
import os
filename = "[Link]"
# Get the current working directory
current_directory = [Link]()
# Join the directory and filename
full_path = [Link](current_directory, filename)
# Get the absolute path
absolute_path = [Link](full_path)
print(f"The absolute path of '{filename}' is: {absolute_path}")
Q9 a) Differentiate between class variables and object variables with an example
Answer: Class variables are shared among all instances of a class, while object (instance)
variables are unique to each instance.
Explanation:
Class Variables:
Defined directly within the class body but outside any method.
Accessed using ClassName.variable_name or self.variable_name (though class name is
preferred for clarity).
Changes to a class variable affect all instances.
Object (Instance) Variables:
Defined inside methods, typically within the __init__ method using self.variable_name.
Unique to each object instance.
Changes to an instance variable only affect that specific instance.
Example:
Python
class Car:
wheels = 4 # Class variable, shared by all cars
def __init__(self, color):
[Link] = color # Instance variable, unique to each car
car1 = Car("Red")
car2 = Car("Blue")
print(f"Car 1 color: {[Link]}, wheels: {[Link]}")
print(f"Car 2 color: {[Link]}, wheels: {[Link]}")
[Link] = 3 # Modifying the class variable
print(f"Car 1 wheels after change: {[Link]}") # Both instances see the change
print(f"Car 2 wheels after change: {[Link]}")
Q9 b) Analyze the significance of garbage collection in python how does python handle
object destruction?
Answer: Garbage collection is significant for automatically managing memory by reclaiming
space occupied by objects that are no longer in use, preventing memory leaks.
Explanation:
Significance: It automates memory management, freeing the programmer from manually
allocating and deallocating memory. This leads to more robust applications with fewer
memory-related bugs.
Python's Handling: Python uses a combination of two strategies for object destruction:
Reference Counting: This is the primary method. Python keeps a count of how many
references point to an object. When the reference count drops to zero, the object is
immediately deallocated.
Generational Garbage Collector: This secondary collector handles reference cycles (where
objects refer to each other, so their reference counts never reach zero). It periodically checks
for these cycles and reclaims the memory for objects within them.
Q9 c) Describe classes and objects in detail
Answer: A class is a blueprint for creating objects, and an object is an instance of a class.
Explanation:
Class:
A template or prototype that defines the structure (attributes/variables) and behavior
(methods/functions) that all objects created from it will have.
It does not occupy memory when defined; it is just a logical construct.
Example: A Car class defines that all cars have color, make (attributes) and
can drive() or brake() (methods).
Object:
A concrete, real-world entity created from a class.
Each object has its own unique state (values for its attributes) and identity.
It occupies memory when instantiated.
Example: A specific red Toyota is an object of the Car class, with color = "Red" and make =
"Toyota".
Q10 a) Explain the role of init() and del() methods in object lifecycle
Answer: The __init__() method is a constructor used for object initialization, while
the __del__() method is a destructor used for cleanup before an object is destroyed.
Explanation:
__init__() Method:
Role: It is automatically called immediately after an object has been created (instantiated)
from a class.
Use: Its primary use is to initialize the object's instance variables with the starting values
provided when the object is created.
__del__() Method:
Role: It is a destructor called when an object is about to be destroyed (garbage collected).
Use: It is used for final cleanup activities, such as closing files, releasing external resources,
or ending network connections before the object's memory is reclaimed.
Q10 b) Distinguish between public and private members of a class with proper examples.
Answer: Public members are accessible from anywhere, while private members have
restricted access, typically only within the class itself.
Explanation:
Public Members:
Access: Can be accessed from outside the class, by any other part of the program.
Python: By default, all members (attributes and methods) in Python are public.
Example: [Link] is public.
Private Members:
Access: Intended to be accessed only within the methods of the class.
Python: Python does not strictly enforce privacy but uses a convention: prefixing a member
name with double underscores (e.g., __salary) makes it "private" through name mangling,
making it harder to access from outside.
Example: self.__salary is private.
Example:
Python
class Employee:
def __init__(self, name, salary):
[Link] = name # Public attribute
self.__salary = salary # Private attribute (by convention/mangling)
def get_salary(self): # Public method to access private data
return self.__salary
emp = Employee("Alice", 50000)
print(f"Name (Public): {[Link]}")
print(f"Salary (via method): {emp.get_salary()}")
# Attempting direct access to private member will likely fail (mangled name needed)
try:
print(f"Salary (Direct access): {emp.__salary}")
except AttributeError as e:
print(f"Error accessing private member directly: {e}")
Q10 c) Describe data abstraction & Encapsulation in detail
Answer: Encapsulation is the bundling of data and methods that operate on that data within
a single unit (class), while abstraction is the concept of hiding complex implementation
details and showing only essential features.
Explanation:
Encapsulation:
Detail: It involves wrapping the data (attributes) and the code that manipulates the data
(methods) into a single entity (an object/class).
Purpose: The main goal is to control access to the data, typically by making attributes private
and providing public methods (getters/setters) to interact with them, ensuring data integrity.
Abstraction:
Detail: It means dealing with ideas rather than events. It focuses on what an object does
instead of how it does it.
Purpose: It simplifies complex systems by breaking them down into manageable, logical
components and hiding unnecessary complexity from the user (programmer using the
class). A car's driver interacts with the steering wheel and pedals (abstraction) without
needing to know the internal combustion engine's mechanics (hidden complexity).