Python
Python
Solution
Section A
1 a. == checks for value equality, while is checks for object identity (if they refer to the same object in
memory).
C. Yes, you can use else with a for loop in Python. The else block is executed after the loop completes
normally, meaning it doesn't encounter a break statement.
e. The split() method in Python is used to divide a string into a list of substrings based on a specified
delimiter (by default, any whitespace). It splits the string wherever the delimiter occurs and returns the
resulting substrings as list elements.
f. When readline() reaches the end of a file, it returns an empty string ''.
Section B
2 a. Dynamic typing in Python means that the type of a variable is determined at runtime, rather than at
compile-time. This allows variables to change their type as the program executes, based on the value
that is assigned to them. In contrast to statically typed languages, where the type of a variable must be
declared and cannot change, Python variables are more flexible.
x = 10 # x is an integer
Explanation:
1. Initial Assignment:
o x is first assigned the value 10. Python dynamically determines that x is an integer, so it
is stored as an int type.
2. Reassignment:
o The variable x is then reassigned the string value "Hello". Python no longer considers x
an integer; instead, it is now a string (str type).
3. Further Reassignment:
o Finally, x is reassigned a list [1, 2, 3]. Python now treats x as a list (list type).
Key Points:
No Type Declaration: Python does not require you to declare the type of a variable. The type is
inferred from the assigned value.
Type Flexibility: A variable can be reassigned to values of different types during the program's
execution, and Python will adjust accordingly.
Memory Efficiency: Dynamic typing can make Python more flexible and easier to write but may
lead to less memory-efficient code, as the type of variables can change frequently.
Implications:
Dynamic typing offers great flexibility, making Python easier and faster to write code in, especially for
quick prototyping or scripting. However, this flexibility also means that Python programs might be more
prone to type-related errors if not carefully managed, as type mismatches can occur at runtime. For this
reason, understanding and effectively managing dynamic typing is important for writing robust Python
code.
2B.
In Python, a list is a collection of items that are ordered, changeable (mutable), and allow duplicate
elements. Lists are defined using square brackets [], and items within the list are separated by commas.
numbers = [1, 2, 3, 4, 5]
Ordered: The items in a list have a defined order, and that order will not change unless explicitly
changed.
Mutable: Lists can be modified after they are created. You can add, remove, or change items in
a list.
To remove duplicates from a list, one common approach is to convert the list to a set, which inherently
removes duplicates because sets do not allow duplicate elements. After that, you can convert the set
back to a list if you need to maintain the list format.
original_list = [1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 9, 9]
unique_set = set(original_list)
unique_list = list(unique_set)
unique_list.sort()
In Python, a function is a reusable block of code that performs a specific task. Functions help
organize and modularize code, making it more readable, maintainable, and reusable. They allow
you to encapsulate code into a single entity, which can then be called and executed whenever
needed.
1. Function Definition: This is where you define what the function does. It starts with the
def keyword, followed by the function name and parentheses. Inside the parentheses, you
can specify parameters (input values) that the function accepts.
2. Function Body: The indented block of code following the function definition, which
contains the statements that define what the function does.
3. Return Statement: A function can return a value using the return statement. This is
optional; if no return is specified, the function returns None by default.
4. Function Call: To execute a function, you use its name followed by parentheses. If the
function requires arguments, you pass them inside the parentheses.
1. Function Name:
2. Parameters:
3. Function Body:
o It then iterates over each number in the list numbers, adding each number to total.
o After the loop, the function returns the sum of the numbers.
4. Return Value:
o The return statement provides the sum of the numbers as the output of the function.
2 D. To read a file named ABC.txt and count the number of lines, words, and characters, you can use the
following Python program. This program will open the file, read its contents, and then use loops and
string methods to perform the counting
def count_file_contents(filename):
# Initialize counters
num_lines = 0
num_words = 0
num_characters = 0
try:
num_lines += 1
num_characters += len(line)
words = line.split()
num_words += len(words)
except FileNotFoundError:
return
# Print the results
filename = 'ABC.txt'
count_file_contents(filename)
2E. Matplotlib is a popular Python library used for creating static, animated, and interactive
visualizations. The most common use of Matplotlib is to create plots and graphs to visualize data.
Basic Components:
1. Importing Matplotlib:
o Typically, you start by importing the pyplot module from Matplotlib, which provides a
MATLAB-like interface for plotting.
2. Creating Data:
o Define the data you want to plot, usually in the form of lists or arrays.
3. Creating a Plot:
o Use functions like plot(), scatter(), bar(), etc., to create different types of plots.
o Customize the plot by adding titles, labels, legends, and adjusting other visual elements.
python
Copy code
x = [1, 2, 3, 4, 5]
# Add a title
plt.xlabel('x values')
plt.ylabel('y values')
# Add a legend
plt.legend()
plt.show()
Explanation
1. Importing Matplotlib:
o import matplotlib.pyplot as plt: Imports the pyplot module from Matplotlib, giving it the
alias plt.
2. Defining Data:
3. Creating a Plot:
marker='o' specifies that each data point should be marked with a circle.
o plt.legend(): Displays the legend based on the label provided in the plot() function.
o plt.show(): Displays the plot in a window. This is the final step and will render the graph
on your screen.
2. Ensure you have Matplotlib installed. If not, you can install it using pip:
python plot_graph.py
Section C
Loops in Python allow you to execute a block of code repeatedly. There are two main types of loops in
Python: for loops and while loops.
for Loop
The for loop in Python is used to iterate over a sequence (like a list, tuple, string, or range) and execute a
block of code for each item in the sequence. It is commonly used when you know in advance how many
times you need to execute a block of code.
# Code to execute
Example
print(fruit)
output:
apple
banana
cherry
This function returns the Least Common Multiple (LCM) of two integers.
Parameters:
Returns:
"""
gcd = math.gcd(a, b)
return lcm_value
"""
This function finds and returns the common letters between two strings.
Parameters:
Returns:
"""
set1 = set(str1)
set2 = set(str2)
common_chars = set1.intersection(set2)
return common_chars
print(char)
4B. To find the sum of all the values in a dictionary, you can use Python's built-in functions and
methods. Specifically, you can use the values() method to get the values from the dictionary and then
use the sum() function to compute the total.
def sum_dictionary_values(d):
"""
Parameters:
Returns:
# Get the values from the dictionary and compute the sum
total_sum = sum(d.values())
return total_sum
# Define a dictionary
result = sum_dictionary_values(d)
A set in Python is an unordered collection of unique elements. Sets are a built-in data type that provide
functionality for storing and manipulating groups of items without duplicates.
Characteristics of Sets
1. Unordered: Sets do not maintain any particular order of elements. The order of elements can
change when they are added or removed.
2. Unique Elements: Sets automatically ensure that all elements are unique. Duplicate elements
are not allowed.
3. Mutable: Sets are mutable, meaning you can add or remove elements after the set has been
created.
4. No Indexing: Unlike lists or tuples, sets do not support indexing, slicing, or other sequence-like
behavior.
5. Hashable Elements: Elements of a set must be hashable, which means they must be immutable
(e.g., numbers, strings, tuples). Lists or other sets cannot be added to a set.
Creating a Set
my_set = {1, 2, 3, 4}
# Define a set
my_set = {1, 2, 3}
my_set.add(4)
You can remove elements from a set using the remove(), discard(), or pop() methods.
1. remove(element): Removes the specified element. If the element is not found, it raises a
KeyError.
2. discard(element): Removes the specified element if it exists. If the element is not found, it does
nothing (no error is raised).
3. pop(): Removes and returns an arbitrary element from the set. Since sets are unordered, you
cannot specify which element to remove.
# Define a set
my_set = {1, 2, 3, 4}
removed_element = my_set.pop()
print(my_set) # Output: {1, 3, 4} or some other set without the removed element
5B. Lambda Functions: Lambda functions in Python are anonymous functions defined using the lambda
keyword. They are often used for short, throwaway functions and are typically used in situations where
a function is needed temporarily.
List Comprehensions: List comprehensions provide a concise way to create lists. They consist of an
expression followed by a for clause and optional if clauses.
When opening files in Python, you can specify the mode in which the file should be opened.
Different modes provide different types of access to the file's content. Here are the most
commonly used file opening modes:
ds a file and capitalizes the first letter of every word in the file.
It writes the modified content back to the file or to a new file
"""
This function reads a file, capitalizes the first letter of every word,
Parameters:
output_path (str): Path to the output file where the modified content will be saved
"""
try:
content = file.read()
except FileNotFoundError:
except Exception as e:
capitalize_first_letter(input_file_path, output_file_path)
Generators are a type of iterable, like lists or tuples, but they generate values on the fly and only
when needed. They are a more memory-efficient way to handle large sequences of data because
they yield items one at a time and do not require all the data to be stored in memory at once.
Characteristics of Generators
1. Lazy Evaluation: Generators produce items one at a time and only when requested. This
is known as lazy evaluation or on-the-fly computation.
2. Memory Efficient: Since they generate values one at a time and do not store the entire
sequence in memory, they are particularly useful for large datasets or streams of data.
3. State Preservation: Generators maintain their state between yields. They remember
where they left off and can continue generating values from that point.
4. Simpler Code: Generators can simplify the code needed for iterating over sequences,
especially when the logic for producing elements is complex.
Creating Generators
1. Generator Functions:
o A generator function uses the yield keyword to produce values. Each call to yield
produces the next value in the sequence.
o Unlike regular functions, which return a single value, generator functions return a
generator object that can be iterated over.
2. Generator Expressions:
o Generator expressions are similar to list comprehensions but use parentheses
instead of square brackets. They produce values on the fly and are more memory-
efficient than creating a list.
7A. NumPy provides a comprehensive suite of functions for generating random numbers. These
functions are part of the numpy.random module and allow for generating random numbers in
various distributions and ranges.
import numpy as np
print(random_integers)
A common way to create a DataFrame is from a dictionary where keys are column names and
values are lists of column data.
import pandas as pd
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David'],
df = pd.DataFrame(data)
print(df)