Answer: == compares the values of two objects, while is checks whether they are the same object in memory. For example, a = [1] and b = [1] give a == b as True but a is b as False because they are different list objects. Result: == checks value equality; is checks object identity.
Key Points
Equality and Identity
== compares contents.
is compares memory object identity.
Q1a2MUnit 3 — Defining list and list slicing
Core Concept
Describe the concept of list comprehension with a suitable example
Answer: List comprehension builds a new list in one line: [expression for item in iterable if condition]. Example: squares = [x*x for x in range(6) if x % 2 == 0] gives [0, 4, 16]. Result: It is a compact way to filter and transform items into a list.
Key Points
List Comprehension
Syntax: [expression for item in iterable if condition].
Combines looping, filtering and collection.
Q1b2MUnit 1 — Python basic Operators
Core Concept
Differentiate between / and // operator with an example
Answer: / performs true division and always returns a float, while // performs floor division and returns an integer quotient. For example, 7 / 2 gives 3.5 and 7 // 2 gives 3. Result: / keeps the fraction; // returns the floored integer quotient.
Key Points
Division Operators
/ returns a float quotient.
// returns the integer floor quotient.
Q1b2MUnit 1 — Python Data Types
Core Concept
How we print the character of a given ASCII value in Python?
Answer: Use the chr() function, which converts an ASCII/Unicode code point to its character.
value = 65
print(chr(value))
Output: A. The reverse function ord('A') returns 65. Result: chr(ascii_value) prints the corresponding character.
Key Points
ASCII Character
chr(65) returns A.
ord() performs the reverse conversion.
Q1c2MUnit 2 — Loop manipulation using pass
Survival ModePredicted
Can you use else with a for loop? If so, when is it executed?
Answer: Yes. Python supports an else clause for for loops. It executes after all iterations finish normally, but not if the loop was stopped by break.
for i in range(3):
print(i)
else:
print('loop finished')
Result: for-else runs only when the loop completes without break.
Key Points
for-else
else belongs to the for statement.
Skipped when break exits the loop.
Q1c2MUnit 3 — Using string data type and string operations
Core Concept
Compute the output of the following python code:
def count(s):
for str in string.split():
s = "&".join(str)
return s
print(count("Python is fun to learn."))
Answer: The code as written raises NameError because the variable string is not defined; s is the parameter. If string.split() were corrected to s.split(), the loop would join each word with '&' and the final value returned would be l&e&a&r&n&. Result: Actual code: NameError. Corrected code would return the last word joined by ampersands.
Key Points
Code Output
string is undefined in the given code.
Using s.split() would return l&e&a&r&n&.
Q1d2MUnit 3 — String
Core Concept
What will be the output of the following Python code? l=[1,0,0,2,′hi′,′′,[]]print(list(filter(bool, l)))
Answer: filter(bool, l) keeps only truthy values. In the list, 1, 2 and 'hi' are truthy; 0, empty string and empty list are falsy. Result: Output: [1, 2, 'hi'].
Key Points
filter with bool
bool keeps truthy values.
Zeros and empty containers are discarded.
Q1d2MUnit 3 — Organizing python codes using functions
Core Concept
How to use the functions defined in library.py in main.py
Answer: Put both files in the same folder and import the module by filename without the .py extension.
library.py
def add(a, b):
return a + b
main.py
import library
print(library.add(3, 4))
Alternatively use from library import add and call add(3, 4). Result: import library or from library import name makes functions from library.py available in main.py.
Key Points
Modules
Import by module name without .py.
Use module.function or direct imported names.
Q1e2MUnit 3 — string manipulation methods
Core Concept
Describe the purpose of the split() method in string manipulation.
Answer: split() divides a string into a list of substrings using a separator; with no argument it splits on whitespace. For example, 'a b c'.split() gives ['a', 'b', 'c']. Result: split() converts text into a list of parts.
Key Points
split()
Default separator is whitespace.
Returns a list of tokens.
Q1e2MUnit 5 — Simple programs using the built-in functions of packages matplotlib
Survival ModePredicted
Describe the difference between linspace and argspace.
linspace and arange both build arrays of numbers. linspace fixes the number of values and includes the end point, spreading the values evenly. arange fixes the step between values and excludes the end point. Use linspace when a count is known and arange when a step is known.
Key Points
linspace fixes the number of values
linspace includes the end point
arange fixes the step and excludes the end
Q1f2MUnit 3 — List manipulation
Core Concept
Explain why the program generates an error.
x = ['12', 'hello', 456]
x[0] *= 3
x[1][1] = 'bye'
Answer: x[0] *= 3 changes the string '12' into '121212' because string multiplication is valid. The next statement x[1][1] = 'bye' raises TypeError because strings are immutable and individual characters cannot be assigned. Result: The error occurs at x[1][1] = 'bye' due to string immutability.
Key Points
List Error
x[0] *= 3 repeats the string.
String characters cannot be reassigned.
Q1f2MUnit 4 — readline()
Core Concept
What does the readline() function return when it reaches the end of a file?
When readline reaches the end of a file it returns an empty string. That empty value signals that no characters remain, so a loop can stop reading. Comparing each returned line with the empty string is the standard way to detect the end of file in Python.
Key Points
Returns an empty string at end of file
Signals that no more lines exist
Loop stops on the empty string
Q1g2MUnit 5 — Simple programs using the built-in functions of packages matplotlib
Core Concept
Which function is used to create identity matrix in NumPy?
Answer: NumPy's np.eye(n) creates an n by n identity matrix with ones on the diagonal and zeros elsewhere. For example, np.eye(3) returns a 3x3 identity matrix. Result: Use np.eye(n).
Key Points
Identity Matrix
np.eye(n) creates identity matrix.
Diagonal elements are one.
Q1g2MUnit 5 — Simple programs using the built-in functions of packages matplotlib
Core Concept
Describe about different functions of matplotlib and pandas.
Answer: Matplotlib functions include plot(), scatter(), bar(), pie(), hist(), title(), xlabel(), ylabel(), legend(), subplot() and show(). Pandas functions include read_csv(), head(), tail(), info(), describe(), groupby(), merge(), dropna(), fillna(), sort_values() and pivot_table(). Result: Matplotlib visualises data; pandas loads, cleans and analyses data.
Key Points
Matplotlib and Pandas
Matplotlib: plot, bar, pie, hist and show.
Pandas: read_csv, groupby, describe and clean data.
Section B
7 Marks Each · 10 questions
Q2a7MUnit 1 — Python variables
Core Concept
Explain the concept of dynamic typing in Python with an example.
Answer: Dynamic typing means a variable's type is decided at runtime and can change when a new value is assigned; no type declaration is needed.
x = 10
print(type(x))
x = 'Hello'
print(type(x))
The type changes from int to str. Python checks type compatibility when operations are performed.\
Dynamic typing in Python. In a statically typed language the type of every variable is fixed when the program is compiled. Python instead binds names to objects at runtime, and the type belongs to the object rather than to the name. A statement that assigns a value creates a reference from the name to an object, and the interpreter records the type of that object. Because the name is only a label, a later assignment may bind the same name to an object of a different type, and the program remains valid as long as the operations performed on the new object are supported. The built-in type function shows the current class of the object bound to a name. Python is strongly typed even though it is dynamically typed, which means that an operation such as adding a string to an integer raises a TypeError instead of silently converting one operand. Duck typing follows from this model: code does not check the declared type of an argument, it simply uses the operations it needs, and any object that supports those operations works. Names are not boxes that hold values but references to objects, which explains why two names can refer to the same mutable list and why changing it through one name is visible through the other. A good answer defines dynamic typing, contrasts it with static typing, shows one name holding an integer and later a string with the reported types, and explains that errors appear at runtime rather than at compile time.
Result: The same variable can hold different types at different times in Python.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(n\log n)$ $O(1)$
Key Points
Dynamic Typing
Types are inferred at runtime.
A variable can be rebound to another type.
Q2a7MUnit 3 — Use of Tuple data type
Core Concept
Illustrate Unpacking tuples, mutable sequences, and string concatenation with examples
Answer: Tuple unpacking assigns elements to separate names: a, b = (10, 20). Mutable sequences such as lists can be changed: L = [1, 2]; L.append(3). String concatenation joins strings: 'Hi' + '!' gives 'Hi!'.\
Lists and tuples compared. A list and a tuple are both ordered sequences that support indexing, slicing, iteration, concatenation and repetition, and both may contain objects of any type. The essential difference is mutability. A list can be changed after creation: elements may be assigned, appended, inserted or removed, and its length may grow or shrink. A tuple cannot be changed, so an attempt to assign to one of its positions raises a TypeError. Tuples are written with parentheses, although the parentheses are often optional, and a one element tuple needs a trailing comma. Lists are written with square brackets. Because tuples are immutable they can be hashed, so a tuple of hashable values may be used as a dictionary key or as an element of a set, while a list cannot. Tuples generally use slightly less memory and are a little faster to create and access, which makes them suitable for fixed records such as coordinates. Multiple values separated by commas are packed into a tuple, and tuple unpacking assigns them to several names in one statement; the star form collects the remaining items into a list. Mutable sequences such as lists can be modified through any name that refers to them, which is why copying requires care. A good answer compares the two in a table covering syntax, mutability, methods, hashability and typical use, and gives an example that succeeds on a list and fails on a tuple.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(n\log n)$ $O(1)$
Key Points
Tuple Unpacking
a, b = tuple assigns each element.
Lists are mutable; strings join with +.
Q2b7MUnit 3 — Defining list and list slicing
Core Concept
Explain how to define a list in Python. Write a Python program to remove duplicates from a list and print the resulting list.
Answer: A list is defined with square brackets, for example L = [1, 2, 2, 3]. To remove duplicates while preserving order:
L = [1, 2, 2, 3, 1, 4]
unique = []
for x in L:
if x not in unique:
unique.append(x)
print(unique)
Output: [1, 2, 3, 4].\
Lists and list operations. A list is an ordered, mutable sequence written with square brackets and commas. Because it is mutable, elements can be replaced, inserted and removed in place, and the list keeps its identity after the change. Lists may hold objects of any type and may be nested, which makes them suitable for tables and records. Indexing and slicing work as for strings, and slice assignment can replace, insert or delete a range in one operation. The append method adds one element at the end, extend adds all elements of another iterable, and insert places an element at a position. The remove method deletes the first matching value and raises an error when it is absent, while pop deletes by position and returns the value. The sort method orders the list in place and reverse reverses it. The count and index methods report occurrences and positions. The membership operator scans the list. Removing duplicates while keeping the original order is done by building a new list and appending each value only when it is not already present, because converting to a set would lose the order. A function that returns the shortest of several nested lists keeps one candidate and compares lengths with a strict test so that the first of equal length wins. A good answer defines the list, explains mutability, lists the methods used, and presents the program with its input and output.
Result: The program keeps the first occurrence of each value.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(1)$ $\&$ $a\& b, a|b, a^b$
Key Points
Defining Lists
Lists are ordered mutable sequences in square brackets.
Unique list can be built with membership checks.
Q2b7MUnit 3 — Defining list and list slicing
Core Concept
Illustrate different list slicing constructs for the following operations on the following list: L = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Return a list of numbers starting from the last to second item of the list
Return a list that start from 3rd item to second last item.
Return a list that has only even position elements of list L to list M.
Return a list that starts from the middle of the list L.
Return a list that reverses all the elements starting from element at index 0 to middle index only and return the entire list. Divide each element of the list by 2 and replace it with the remainder.
Answer:
L = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(L[-1:0:-1]) # 9,8,7,6,5,4,3,2
print(L[2:-1]) # 3,4,5,6,7,8
M = L[1::2]
print(M) # 2,4,6,8 at even positions
print(L[4:]) # 5,6,7,8,9 from middle
L[:5] = L[:5][::-1]
print([x % 2 for x in L]) # remainder after dividing by 2
Slicing sequences. A slice selects part of a sequence with the syntax start, stop and step inside square brackets, separated by colons. The start index is included and the stop index is excluded. Any part may be omitted, in which case the start defaults to the beginning, the stop to the end and the step to one. Negative indices count from the end, so minus one is the last element. A negative step walks backwards, and a step of minus one therefore reverses the sequence. Slice assignment on a list replaces the selected range and may change the length of the list. Slicing a string returns a string and slicing a tuple returns a tuple. Selecting every second element is done with a step of two, and starting from index one gives the elements at even positions when positions are counted from one. The last element down to the second element is expressed with a start of minus one and a stop of zero with a step of minus one, remembering that the stop is excluded. The middle of a sequence is the length divided by two, truncated to an integer. Out of range bounds are clamped rather than raising an error, which makes slices forgiving. A good answer tabulates the requested operations with the exact slice expression and the resulting list for the given data, then presents the program.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(n\log n)$ $O(1)$
Key Points
List Slicing
L[-1:0:-1] goes from last to second item.
L[1::2] selects even positions.
Q2c7MUnit 3 — Python Functions
Core Concept
Explain the concept of functions in Python. Write a function that takes a list of numbers and returns the sum of all the numbers in the list.
Answer:
def sum_list(numbers):
total = 0
for x in numbers:
total += x
return total
print(sum_list([1, 2, 3, 4]))
Output: 10.\
Defining and using functions. A function is a named block of statements that performs a task and may return a value. It is defined with the def keyword, a name, a parameter list in parentheses and a colon, followed by an indented body. Calling the function by name with arguments executes the body and binds each argument to the corresponding parameter. A return statement sends a value back to the caller and ends the function; a function without a return statement returns None. Parameters may have default values, which must come after parameters without defaults, and arguments may be passed by position or by keyword. Names created inside a function are local and disappear when it finishes, while a name from the enclosing scope can be read but is only modified with the global statement, which should be avoided. Functions may call other functions, including themselves, which is recursion. A docstring placed immediately after the definition documents purpose and parameters. Functions are the main tool for avoiding repetition: a calculation written once can be reused and tested once. A good answer defines the syntax, explains parameters and return values, distinguishes local from global scope, and then presents the requested function with a sample call and its result. It should trace the steps for a sample input and explain the guard for an invalid case.
Result: The function adds all list elements and returns the total.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(n\log n)$ $O(1)$
Key Points
Functions and Lists
Use a loop and accumulator.
return produces the final sum.
Q2c7MUnit 3 — Python Functions
Core Concept
Construct a function perfect_square(number) that returns a number if it is a perfect square otherwise it returns -1. For example: perfect_square(1) returns 1, perfect_square(2) returns -1
Answer:
def perfect_square(number):
root = int(number ** 0.5)
return number if root * root == number else -1
print(perfect_square(1)) # 1
print(perfect_square(2)) # -1
The function returns the original number for a perfect square and -1 otherwise.\
Defining and using functions. A function is a named block of statements that performs a task and may return a value. It is defined with the def keyword, a name, a parameter list in parentheses and a colon, followed by an indented body. Calling the function by name with arguments executes the body and binds each argument to the corresponding parameter. A return statement sends a value back to the caller and ends the function; a function without a return statement returns None. Parameters may have default values, which must come after parameters without defaults, and arguments may be passed by position or by keyword. Names created inside a function are local and disappear when it finishes, while a name from the enclosing scope can be read but is only modified with the global statement, which should be avoided. Functions may call other functions, including themselves, which is recursion. A docstring placed immediately after the definition documents purpose and parameters. Functions are the main tool for avoiding repetition: a calculation written once can be reused and tested once. A good answer defines the syntax, explains parameters and return values, distinguishes local from global scope, and then presents the requested function with a sample call and its result. It should trace the steps for a sample input and explain the guard for an invalid case.
Result: Compare the integer square root squared with the number.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(n\log n)$ $O(1)$
Key Points
Perfect Square
Use int(number ** 0.5).
Return number or -1.
Q2d7MUnit 4 — Reading files
Survival ModePredictedRepeated
Construct a program to change the contents of the file by reversing each character separated by comma: Hello!! Output H,e,l,l,o,!,!
Answer:
with open('data.txt', 'r') as f:
data = f.read()
result = ','.join(reversed(data))
with open('reverse.txt', 'w') as f:
f.write(result)
print(result)
If the file contains Hello, the output is H,e,l,l,o.\
Reading files. A file is opened with the open function, which returns a file object, and the mode argument decides the permitted operations. The mode r opens an existing file for text reading. The preferred pattern uses a with statement, because the file is closed automatically even when an error occurs. The read method returns the entire remaining contents as one string, readline returns the next line including its newline, and readlines returns a list of the remaining lines. A file object can also be iterated directly, which yields one line at a time and is the most memory efficient choice for large files. At the end of the file, readline returns an empty string, which is the standard signal that no more data is available. Counting lines, words and characters is done by reading the text once and applying splitlines, split and len, or by counting newline characters while iterating. The encoding should be given explicitly when the text is not plain ASCII. Reading a file in binary mode returns bytes, which must be decoded before text operations. Reversing the contents character by character means reversing the string and joining the characters with the requested separator. A good answer explains the modes, shows the with statement, describes each read method and its return value, and then presents the program with a sample file and its exact output.
Result: read() obtains the text, reversed() reverses characters and join() separates them by commas.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(n\log n)$ $O(1)$
Key Points
Reversing File Content
File data is a string of characters.
join with comma produces the required format.
Q2d7MUnit 4 — Reading files
Core Concept
Write a Python program to read a file named "ABC.txt" and count the number of lines, words, and characters in the file.
Answer:
with open('ABC.txt', 'r') as f:
data = f.read()
lines = len(data.splitlines())
words = len(data.split())
chars = len(data)
print('Lines:', lines, 'Words:', words, 'Characters:', chars)
Reading files. A file is opened with the open function, which returns a file object, and the mode argument decides the permitted operations. The mode r opens an existing file for text reading. The preferred pattern uses a with statement, because the file is closed automatically even when an error occurs. The read method returns the entire remaining contents as one string, readline returns the next line including its newline, and readlines returns a list of the remaining lines. A file object can also be iterated directly, which yields one line at a time and is the most memory efficient choice for large files. At the end of the file, readline returns an empty string, which is the standard signal that no more data is available. Counting lines, words and characters is done by reading the text once and applying splitlines, split and len, or by counting newline characters while iterating. The encoding should be given explicitly when the text is not plain ASCII. Reading a file in binary mode returns bytes, which must be decoded before text operations. Reversing the contents character by character means reversing the string and joining the characters with the requested separator. A good answer explains the modes, shows the with statement, describes each read method and its return value, and then presents the program with a sample file and its exact output.
Result: splitlines(), split() and len() count lines, words and characters respectively.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(n\log n)$ $O(1)$
Key Points
File Statistics
splitlines() counts lines.
split() counts words; len counts characters.
Q2e7MUnit 5 — Simple programs using the built-in functions of packages matplotlib
Survival ModePredictedRepeated
Explain the basic usage of matplotlib for plotting graphs. Write a Python program to plot a simple line graph showing the relationship between x=[1,2,3,4,5] and y=[1,4,9,16,25].
Answer: Matplotlib is a plotting library used to create visualisations. pyplot provides figure, plot, title, xlabel, ylabel, legend and show.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y, marker='o')
plt.title('Simple Line Graph')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
Plotting with Matplotlib. Matplotlib is a plotting library that turns numbers into figures. Its pyplot interface keeps a current figure and a current set of axes, so short scripts can call plotting functions directly. The plot function draws a line through the given x and y values and accepts a marker, a line style and a colour. Bar draws vertical bars, scatter draws points, pie draws proportional slices and hist draws a distribution. Titles and axis labels give the figure meaning, the legend identifies each series using the label argument, and grid draws reference lines. The show function opens an interactive window, while savefig writes the figure to a file. Figures and axes objects give finer control when several plots share one image. Colours may be named or given as hex values, and the figure size is set in inches with a dots per inch value that controls resolution. Data must be prepared before plotting: lists or arrays of equal length, with missing values removed or filled. Choosing the right chart matters, because a line suggests a trend along an ordered axis, bars compare categories, a pie shows parts of a whole and a scatter shows the relation between two measures. A good answer explains the workflow of import, prepare data, plot, label, and display, then presents the requested program with its data and describes what the figure shows.
Result: plt.plot draws the line and plt.show displays it.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(n\log n)$ $O(1)$
Key Points
Matplotlib
Import matplotlib.pyplot as plt.
plot() draws; title and labels annotate.
Q2e7MUnit 5 — Simple programs using the built-in functions of packages matplotlib
Answer: A grouped bar chart can compare calories, potassium and fat for each food.
import matplotlib.pyplot as plt
import numpy as np
foods = ['Meat', 'Banana', 'Avocados', 'Sweet Potatoes', 'Spinach', 'Watermelon', 'Coconut water', 'Beans', 'Legumes', 'Tomato']
cal = [250, 130, 140, 120, 20, 20, 10, 50, 40, 19]
pot = [40, 55, 20, 30, 40, 32, 10, 26, 25, 20]
fat = [8, 5, 3, 6, 1, 1.5, 0, 2, 1.5, 2.5]
x = np.arange(len(foods))
plt.bar(x - 0.2, cal, 0.2, label='Calories')
plt.bar(x, pot, 0.2, label='Potassium')
plt.bar(x + 0.2, fat, 0.2, label='Fat')
plt.xticks(x, foods, rotation=45, ha='right')
plt.legend(); plt.tight_layout(); plt.show()
Plotting with Matplotlib. Matplotlib is a plotting library that turns numbers into figures. Its pyplot interface keeps a current figure and a current set of axes, so short scripts can call plotting functions directly. The plot function draws a line through the given x and y values and accepts a marker, a line style and a colour. Bar draws vertical bars, scatter draws points, pie draws proportional slices and hist draws a distribution. Titles and axis labels give the figure meaning, the legend identifies each series using the label argument, and grid draws reference lines. The show function opens an interactive window, while savefig writes the figure to a file. Figures and axes objects give finer control when several plots share one image. Colours may be named or given as hex values, and the figure size is set in inches with a dots per inch value that controls resolution. Data must be prepared before plotting: lists or arrays of equal length, with missing values removed or filled. Choosing the right chart matters, because a line suggests a trend along an ordered axis, bars compare categories, a pie shows parts of a whole and a scatter shows the relation between two measures. A good answer explains the workflow of import, prepare data, plot, label, and display, then presents the requested program with its data and describes what the figure shows.
Result: The code plots the given food dataset as grouped bars.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(n\log n)$ $O(1)$
Key Points
Matplotlib Dataset Plot
Store each column as a list.
Use grouped bars for comparison.
Section C
7 Marks Each · 18 questions
Q3a7MUnit 2 — Use of while loops in python
Survival ModePredictedRepeated
Explain for and while loops used in Python with appropriate example.
Answer: A for loop iterates over a sequence, while a while loop repeats while a condition is true.
for i in range(1, 6):
print(i)
i = 1
while i < = 5:
print(i)
i += 1
Both print 1 to 5. Use for when the number of items is known and while when repetition depends on a condition.\
Looping constructs in Python. A loop repeats a block of statements. Python provides two loop statements and no do while form. The for loop obtains items from an iterable, which may be a range of numbers, a string, a list, a tuple, a dictionary or a file, and runs once for each item. The range function generates a sequence from a start value up to but excluding a stop value, with an optional step, and a negative step counts down. The while loop repeats as long as its condition remains true, so the body must change something that the condition depends on, otherwise the loop never ends. A loop may be exited early with break, and continue skips the rest of the current iteration and moves to the next one. Both statements also support an else clause that runs only when the loop finishes without a break, which is useful for searches. Nested loops place one loop inside another and are used for tables and patterns. The correct choice depends on the problem: for is clearer when the number of items or the sequence is known, while while suits repetition that depends on a condition such as reading until a sentinel value appears. A good answer explains both forms, shows the syntax, compares them in a short table and then presents the requested program. It should trace one or two iterations, show the output and mention the risk of an infinite loop when the condition variable is not updated.
Result: for iterates over items; while repeats until its condition becomes false.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(n\log n)$ $O(1)$
Key Points
for and while loops
for works over an iterable.
while works until a condition fails.
Q3a7MUnit 3 — Programming using string
Core Concept
Python function removenth(s, n) that takes as input a string and an integer n≥0 and then removes a character at index n. If n is beyond the length of s, whole s is returned. For example:
removenth("MANGO", 1) returns "MNGO"
removenth("MANGO", 3) returns "MANO"
Answer:
def removenth(s, n):
if n >= len(s):
return s
return s[:n] + s[n + 1:]
print(removenth('MANGO', 1)) # MNGO
print(removenth('MANGO', 3)) # MANO
Slicing sequences. A slice selects part of a sequence with the syntax start, stop and step inside square brackets, separated by colons. The start index is included and the stop index is excluded. Any part may be omitted, in which case the start defaults to the beginning, the stop to the end and the step to one. Negative indices count from the end, so minus one is the last element. A negative step walks backwards, and a step of minus one therefore reverses the sequence. Slice assignment on a list replaces the selected range and may change the length of the list. Slicing a string returns a string and slicing a tuple returns a tuple. Selecting every second element is done with a step of two, and starting from index one gives the elements at even positions when positions are counted from one. The last element down to the second element is expressed with a start of minus one and a stop of zero with a step of minus one, remembering that the stop is excluded. The middle of a sequence is the length divided by two, truncated to an integer. Out of range bounds are clamped rather than raising an error, which makes slices forgiving. A good answer tabulates the requested operations with the exact slice expression and the resulting list for the given data, then presents the program.
Result: Slicing before and after index n removes that character.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(n\log n)$ $O(1)$
Key Points
String Removal
s[:n] keeps characters before n.
s[n+1:] keeps characters after n.
Q3b7MUnit 2 — Programming using Python conditional and loop blocks
Survival Mode
Write a Python Program to find the LCM of two numbers.
Answer: LCM can be found by using the relation LCM(a, b) = abs(a*b) // GCD(a, b).
import math
a = int(input('First: '))
b = int(input('Second: '))
print('LCM =', abs(a * b) // math.gcd(a, b))
For 12 and 18, gcd is 6 and LCM is 36.\
Finding the least common multiple. The least common multiple of two integers is the smallest positive integer that both divide exactly. Computing it by listing multiples works for small numbers but is slow and unbounded. The standard method uses the greatest common divisor, because the product of two numbers equals the product of their greatest common divisor and their least common multiple. Therefore the least common multiple is the absolute value of the product divided by the greatest common divisor, using integer division. The greatest common divisor is found efficiently by the Euclidean algorithm, which repeatedly replaces the larger number by the remainder of dividing it by the smaller one until the remainder is zero. Python provides that algorithm as math.gcd, so the program only needs the relation. The absolute value matters because negative inputs would otherwise give a negative answer, and zero must be handled separately because the multiple of zero and any number is zero and division by a zero divisor is undefined. A loop based version can also compute the multiple by starting from the larger number and adding it until the result is divisible by the other. A good answer states the relation, explains the Euclidean algorithm in one line, presents the program with the import, the input conversion and the printed result, and works a sample pair such as twelve and eighteen.
Result: The program computes LCM from the greatest common divisor.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(n\log n)$ $O(1)$
Key Points
LCM
LCM = abs(a*b) // gcd(a,b).
math.gcd() finds the greatest common divisor.
Q3b7MUnit 3 — Programming using string
Core Concept
Construct a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically. Suppose the following input is supplied to the program: without, hello, bag, world
Then, the output should be:
bag, hello, without, world
Answer:
s = input()
words = [w.strip() for w in s.split(',')]
print(', '.join(sorted(words)))
For input without, hello, bag, world the output is bag, hello, without, world.\
Strings and string operations. A string is an ordered sequence of characters. It is immutable, so every method that appears to change a string actually returns a new one. Indexing starts at zero and negative indices count from the end. Slicing uses a start, a stop and a step, where the start is included and the stop is excluded, and a step of minus one reverses the sequence. Concatenation uses the plus operator and repetition uses the star operator. The membership operator tests for a substring. Built-in functions report the length and convert the case through methods. Common methods remove surrounding whitespace, replace one substring with another, split a string into a list at a separator, join a list back into a string, find the position of a substring with a minus one result when absent, and count occurrences. Since strings are immutable, repeated concatenation in a loop is inefficient; joining a list of parts is better. Formatted output can be produced with f strings, which embed expressions directly in the text. Iterating a string yields its characters one by one, which makes counting tasks simple. A good answer explains indexing and slicing with the exact results for a sample word, lists the methods used in the question, and then presents the program with its input, output and a short comment for each line. It should mention that string comparison is based on character codes.
Result: Splitting, trimming, sorting and joining produces the required alphabetical sequence.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(1)$ $\&$ $a\& b, a|b, a^b$
Key Points
Sorting Words
split(',') separates words.
sorted() orders alphabetically.
Q4a7MUnit 2 — Programming using Python conditional and loop blocks
Core Concept
A website requires the users to input username and password to register. Construct a program to check the validity of password input by users. Following are the criteria for checking the password:
At least 1 letter between [a-z]
At least 1 number between [0-9]
At least 1 letter between [A-Z]
At least 1 character from [$#@]
Minimum length of transaction password: 6
Maximum length of transaction password: 12
Your program should accept a sequence of comma separated passwords and will check them according to the above criteria. Passwords that match the criteria are to be printed, each separated by a comma
Answer: The code checks each password with regular expressions and length limits.
import re
s = input()
pws = s.split(',')
valid = []
for p in pws:
if (6 < = len(p) < = 12 and re.search('[a-z]', p) and
re.search('[A-Z]', p) and re.search('[0-9]', p) and
re.search('[$#@]', p)):
valid.append(p)
print(','.join(valid))
Only passwords satisfying all six conditions are printed, separated by commas.\
Regular expressions with the re module. A regular expression is a pattern language for describing text. The re module compiles a pattern and applies it to a string. Ordinary characters match themselves, a dot matches any character except a newline, character classes in square brackets match one of a set, and escapes such as backslash d match a digit, backslash w matches a word character and backslash s matches whitespace. Quantifiers control repetition: star means zero or more, plus means one or more, question mark means optional, and braces give an exact or ranged count. Anchors tie a match to the start or end of the string. Parentheses create groups, and the vertical bar gives alternatives. The function match checks only the beginning of the string, search looks anywhere, findall returns every non overlapping match as a list, and finditer returns match objects with positions. The substitution function replaces matches and can take a function that builds the replacement from each match. Patterns should be written as raw strings so that backslashes are not interpreted twice. Compiling a pattern once with compile is more efficient when the same pattern is used repeatedly, and flags can make matching case insensitive. Greedy quantifiers take as much text as possible, and a trailing question mark makes them lazy. A good answer explains the syntax, lists the functions with their return values, shows the requested pattern, then presents a program with sample input and the exact output.
Result: Each password must contain lowercase, uppercase, digit and special character and be 6 to 12 characters long.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(n\log n)$ $O(1)$
Key Points
Password Validation
Use re.search for each required character class.
Check length between 6 and 12.
Q4a7MUnit 3 — String
Core Concept
Write a program takes two strings and checks common letters in both the strings. Enter first string: Hari Enter second string: Hale The common letters are: H
Answer: The program compares characters from both strings.
a = input('Enter first string: ')
b = input('Enter second string: ')
common = sorted(set(a) & set(b))
print('The common letters are:', ', '.join(common))
For Hari and Hale, the letters present in both strings are H and a. If only uppercase common letters are required, filter with if c.isupper().\
Sets and their operations. A set is an unordered collection of unique hashable elements. Duplicate values are discarded automatically, so a set is the natural tool for removing repeated items and for testing membership quickly. A set literal uses braces, and an empty set must be created with the set constructor because empty braces create a dictionary. The main operations are union, intersection, difference and symmetric difference, available both as operators and as named methods. Union combines the elements of both sets, intersection keeps only common elements, difference keeps elements of the first set that are not in the second, and symmetric difference keeps elements that appear in exactly one of the two sets. Sets are mutable, so elements can be added with add, several at once with update, and removed with remove, which raises an error when the element is absent, or discard, which stays silent. Set membership is average constant time because elements are stored by hash, which makes sets faster than lists for large membership tests. Frozensets are immutable and can therefore be used as dictionary keys or as elements of another set. Iteration order is not defined, so a set must be sorted before it is printed in a predictable order. A good answer defines the type, lists each operation with its symbol and method, gives a small example of each result, and then presents the requested program with sample sets, printed output and a short explanation.
Result: Set intersection finds common letters; Hari and Hale share H and a.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(1)$ $\&$ $a\& b, a|b, a^b$
Key Points
Common Letters
Convert strings to sets and intersect.
For sample input, common letters are H and a.
Q4b7MUnit 2 — Use of while loops in python
Core Concept
Explore the working of while, and for loop with examples.
Answer: A while loop checks a condition before every iteration and must update the condition variable.
i = 1
while i < = 3:
print(i)
i += 1
A for loop obtains each item from an iterable automatically.
for x in ['a', 'b', 'c']:
print(x)
Both repeat a block, but for is preferred when iterating known sequences.\
Looping constructs in Python. A loop repeats a block of statements. Python provides two loop statements and no do while form. The for loop obtains items from an iterable, which may be a range of numbers, a string, a list, a tuple, a dictionary or a file, and runs once for each item. The range function generates a sequence from a start value up to but excluding a stop value, with an optional step, and a negative step counts down. The while loop repeats as long as its condition remains true, so the body must change something that the condition depends on, otherwise the loop never ends. A loop may be exited early with break, and continue skips the rest of the current iteration and moves to the next one. Both statements also support an else clause that runs only when the loop finishes without a break, which is useful for searches. Nested loops place one loop inside another and are used for tables and patterns. The correct choice depends on the problem: for is clearer when the number of items or the sequence is known, while while suits repetition that depends on a condition such as reading until a sentinel value appears. A good answer explains both forms, shows the syntax, compares them in a short table and then presents the requested program. It should trace one or two iterations, show the output and mention the risk of an infinite loop when the condition variable is not updated.
Result: while depends on a changing condition; for depends on items in a sequence.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(n\log n)$ $O(1)$
Key Points
while and for
while requires condition update.
for obtains items from an iterable.
Q4b7MUnit 3 — Dictionary manipulation
Core Concept
Write a Python Program to find the sum all the items in a dictionary. For example if d={′A′:100,′B′:540,′C′:239} then output should be 879.
Dictionaries and their operations. A dictionary maps keys to values. Keys must be hashable and unique, and values may be any object. A literal is written with braces and colon separated pairs, and an empty dictionary is written as a pair of braces. Values are read by placing the key in square brackets, which raises a KeyError when the key is absent, or with the get method, which returns a default instead. Assignment creates a new entry when the key is missing and updates it when the key exists. Deleting uses the del statement or the pop method; pop also returns the removed value. The methods keys, values and items return views over the contents, and items yields pairs that unpack neatly in a loop. The update method merges another dictionary into the current one, and a key that appears in both takes the value from the second dictionary. The membership test checks keys, and the length function counts entries. Since recent versions the insertion order is preserved, but a dictionary should still be treated as a mapping rather than an ordered sequence. Common patterns are counting occurrences with get, summing values, grouping items and building a lookup table. A good answer defines the type, lists the create, read, update and delete operations, gives a short example of each, and then presents the requested program with its input, output and a note on the get method.
Result: sum() over values() adds all dictionary items.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(n\log n)$ $O(1)$
Key Points
Dictionary Sum
values() gives the numeric values.
sum() returns their total.
Q5a7MUnit 3 — Programming using string
Core Concept
Construct a function ret_smaller(l) that returns smallest list from a nested list. If two lists have same length then return the first list that is encountered. For example:
ret_smaller([[-2, -1, 0, 0.12, 1, 2], [3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]) returns [3,4,5]
ret_smaller([[-2, -1, 0, 0.12, 1, 2], ['a', 'b', 'c', 'd', 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]) returns [6, 7, 8, 9, 10]
Answer:
def ret_smaller(l):
smallest = l[0]
for item in l[1:]:
if len(item) < len(smallest):
smallest = item
return smallest
print(ret_smaller([[-2, -1], [3, 4, 5], [6, 7, 8, 9]])) # [3, 4, 5]
The strict less-than comparison keeps the first list when lengths are equal.\
Lists and list operations. A list is an ordered, mutable sequence written with square brackets and commas. Because it is mutable, elements can be replaced, inserted and removed in place, and the list keeps its identity after the change. Lists may hold objects of any type and may be nested, which makes them suitable for tables and records. Indexing and slicing work as for strings, and slice assignment can replace, insert or delete a range in one operation. The append method adds one element at the end, extend adds all elements of another iterable, and insert places an element at a position. The remove method deletes the first matching value and raises an error when it is absent, while pop deletes by position and returns the value. The sort method orders the list in place and reverse reverses it. The count and index methods report occurrences and positions. The membership operator scans the list. Removing duplicates while keeping the original order is done by building a new list and appending each value only when it is not already present, because converting to a set would lose the order. A function that returns the shortest of several nested lists keeps one candidate and compares lengths with a strict test so that the first of equal length wins. A good answer defines the list, explains mutability, lists the methods used, and presents the program with its input and output.
Result: The function returns the shortest nested list, preferring the first in a tie.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(1)$ $\&$ $a\& b, a|b, a^b$
Key Points
Nested Lists
Compare lengths of inner lists.
Strict < keeps the first tie.
Q5b7MUnit 3 — Programming using string
Core Concept
Construct following filters:
Filter all the numbers
Filter all the strings starting with a vowel
Filter all the strings that contains any of the following noun: Agra, Ramesh, Tomato, Patna.
Create a program that implements these filters to clean the text.
Answer: Three filters can be written as reusable functions.
numbers = lambda x: isinstance(x, (int, float)) and not isinstance(x, bool)
vowel_start = lambda s: isinstance(s, str) and s[:1].lower() in 'aeiou'
nouns = ('Agra', 'Ramesh', 'Tomato', 'Patna')
has_noun = lambda s: isinstance(s, str) and any(n in s for n in nouns)
data = [12, 'apple', 'Agra road', 7, 'Umbrella', ' Delhi', 'Tomato soup']
print('numbers:', list(filter(numbers, data)))
print('vowel strings:', list(filter(vowel_start, data)))
print('noun strings:', list(filter(has_noun, data)))
Defining and using functions. A function is a named block of statements that performs a task and may return a value. It is defined with the def keyword, a name, a parameter list in parentheses and a colon, followed by an indented body. Calling the function by name with arguments executes the body and binds each argument to the corresponding parameter. A return statement sends a value back to the caller and ends the function; a function without a return statement returns None. Parameters may have default values, which must come after parameters without defaults, and arguments may be passed by position or by keyword. Names created inside a function are local and disappear when it finishes, while a name from the enclosing scope can be read but is only modified with the global statement, which should be avoided. Functions may call other functions, including themselves, which is recursion. A docstring placed immediately after the definition documents purpose and parameters. Functions are the main tool for avoiding repetition: a calculation written once can be reused and tested once. A good answer defines the syntax, explains parameters and return values, distinguishes local from global scope, and then presents the requested function with a sample call and its result. It should trace the steps for a sample input and explain the guard for an invalid case.
Result: filter() applies each predicate to clean the text list.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(n\log n)$ $O(1)$
Key Points
Filters
Numbers are filtered with isinstance.
String filters use first letter and noun membership.
Q5b7MUnit 3 — Organizing python codes using functions
Core Concept
Explain how lambda functions can be used within a list comprehension. Write a Python program that uses a lambda function within a list comprehension to convert a list of temperatures in Celsius to Fahrenheit.
Answer: A lambda can be placed inside a list comprehension to apply a short formula to each item.
celsius = [0, 10, 20, 30, 100]
fahrenheit = [(lambda c: c * 9 / 5 + 32)(c) for c in celsius]
print(fahrenheit)
Output: [32.0, 50.0, 68.0, 86.0, 212.0].\
Lambda functions and comprehensions. A lambda expression creates a small anonymous function in a single expression. Its form is the keyword lambda, a list of parameters, a colon and one expression whose value is returned automatically. Because it is an expression, a lambda can appear wherever a value is expected: as an argument to another function, inside a list, or inside a comprehension. It cannot contain statements, assignments or multiple expressions, so it suits short operations only. The map and filter functions accept a function and an iterable, and sorted accepts a key function, so a lambda is a convenient way to supply the comparison. A list comprehension builds a new list from an iterable and combines the loop with an optional condition in one readable line. Placing a lambda inside a comprehension and calling it immediately on each item applies a formula to every element. The conversion from Celsius to Fahrenheit multiplies by nine, divides by five and adds thirty two. A named function is clearer when the logic is longer than one expression or when it is reused in several places. A good answer explains the syntax, contrasts a lambda with a def, shows how it is used with map, filter and sorted, and then presents the requested program with its input list and output list.
Result: The lambda converts each Celsius value inside the comprehension.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(n\log n)$ $O(1)$
Key Points
Lambda in Comprehension
Lambda defines the conversion expression.
Comprehension applies it to every item.
Q6a7MUnit 4 — Writing files in python
Core Concept
Explain different file opening modes also write a Python Program to read a file and capitalize the first letter of every word in the file.
Answer: r is read, w is write with truncation, a is append, r+ is read/write and b is binary. Program to capitalise words:
with open('input.txt', 'r') as f:
text = f.read()
out = ' '.join(w[:1].upper() + w[1:] for w in text.split())
with open('output.txt', 'w') as f:
f.write(out)
File opening modes. The mode string passed to open decides what the program may do with the file and where the file pointer starts. The basic modes are r for reading an existing file, w for writing from the beginning with truncation, a for appending at the end, and x for exclusive creation. The plus sign adds the missing permission: r plus allows reading and writing without truncating, w plus truncates and then allows both, and a plus appends and allows reading. The letter b selects binary mode and returns bytes, while t selects text mode and is the default. A binary mode can be combined with a plus sign as well. The choice matters because w destroys existing content immediately on opening, even if nothing is written, whereas a preserves it. In text mode newline translation happens automatically, so line endings may differ between platforms, while binary mode gives exact bytes, which is needed for images and for precise positioning. Reading and writing on the same file requires a seek between operations, because the pointer follows the last operation performed. The encoding argument should be supplied for text files that are not plain ASCII. A good answer presents the modes in a table with columns for reading, writing, truncation and pointer position, gives a one line example of each, and explains which mode suits the requested task.
Result: split() isolates words, upper() capitalises the first character and write mode saves the result.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(n\log n)$ $O(1)$
Key Points
Opening Modes and Capitalisation
Choose r to read and w to save output.
Capitalise first character of each token.
Q6a7MUnit 4 — Writing files in python
Core Concept
Change all the numbers in the file to text. Construct a program for the same. Example: Given 2 integer numbers, return their product only if the product is equal to or lower than 10. And the result should be: Given two integer numbers, return their product only if the product is equal to or lower than one zero
Answer: Numbers in text can be replaced with number words using a regular expression.
import re
words = {'0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five'}
s = 'Given 2 integer numbers, return their product only if the product is equal to or lower than 10.'
s = re.sub(r'\d+', lambda m: words.get(m.group(), m.group()), s)
print(s)
Writing files. Writing uses the open function with a mode that permits output. The mode w creates the file when it does not exist and truncates it when it does, so all previous contents are lost. The mode a appends to the end and never truncates, and the mode x creates a new file but fails when the file already exists. The write method accepts one string and returns the number of characters written. The writelines method accepts an iterable of strings and writes them one after another without adding separators, so each line must already end with a newline where one is wanted. Neither method adds a newline automatically. A with statement should be used so that the buffer is flushed and the file is closed, which guarantees that the data reaches the disk. Text mode translates newline characters according to the platform, while binary mode writes bytes unchanged. Building records as lines and then writing them in one call is efficient, and a header line followed by data lines is a common pattern. If a file is both read and written, the pointer must be positioned correctly with seek. A good answer explains the modes, the difference between write and writelines, the newline requirement and the role of flushing, and then presents the requested program. It should show the file contents after the run and note that opening with w destroys the old contents.
Result: The digit tokens 2 and 10 become two and one zero, producing the required text.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(n\log n)$ $O(1)$
Key Points
Number to Text
Use re.sub to find digit tokens.
Map digits to words with a dictionary.
Q6b7MUnit 4 — Reading files
Core Concept
Construct a program which accepts a sequence of words separated by whitespace as file input. Print the words composed of digits only.
Answer:
with open('words.txt', 'r') as f:
text = f.read()
for word in text.split():
if word.isdigit():
print(word)
Reading files. A file is opened with the open function, which returns a file object, and the mode argument decides the permitted operations. The mode r opens an existing file for text reading. The preferred pattern uses a with statement, because the file is closed automatically even when an error occurs. The read method returns the entire remaining contents as one string, readline returns the next line including its newline, and readlines returns a list of the remaining lines. A file object can also be iterated directly, which yields one line at a time and is the most memory efficient choice for large files. At the end of the file, readline returns an empty string, which is the standard signal that no more data is available. Counting lines, words and characters is done by reading the text once and applying splitlines, split and len, or by counting newline characters while iterating. The encoding should be given explicitly when the text is not plain ASCII. Reading a file in binary mode returns bytes, which must be decoded before text operations. Reversing the contents character by character means reversing the string and joining the characters with the requested separator. A good answer explains the modes, shows the with statement, describes each read method and its return value, and then presents the program with a sample file and its exact output.
Result: split() reads whitespace-separated words and isdigit() prints only digit-only words.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(n\log n)$ $O(1)$
Key Points
Digit Words
Read file and split on whitespace.
isdigit() tests all-digit words.
Q7a7MUnit 5 — Simple programs using the built-in functions of packages matplotlib
Core Concept
Describe how to generate random numbers using NumPy. Write a Python program to create an array of 5 random integers between 10 and 50.
Answer: NumPy's random module generates arrays of random values.
import numpy as np
arr = np.random.randint(10, 51, 5)
print(arr)
randint(10, 51, 5) produces five integers from 10 up to 50, since the upper bound is exclusive.\
Numerical work with NumPy. NumPy provides the ndarray, a compact container for values of one type stored in a block of memory. Unlike a list, an array has a fixed shape, a data type and vectorised operations that apply to every element without an explicit loop. Arrays are created from lists, from ranges with arange, from evenly spaced values with linspace, and from random generators. The function arange takes a start, a stop and a step and excludes the stop, while linspace takes a start, a stop and a count and includes both ends. The random module offers rand for uniform values, randn for a standard normal distribution and randint for whole numbers in a half open range, so the upper bound is exclusive. Arithmetic between arrays of the same shape works element by element, and the matrix multiplication operator produces the matrix product rather than the elementwise product. Transpose swaps rows and columns, reshape changes the shape without copying data where possible, and the linear algebra submodule provides determinant, inverse and solve. Aggregations such as sum, mean, minimum and maximum accept an axis argument to work along rows or columns. Slicing and boolean masks select subarrays. A good answer explains the array model, contrasts it with lists, lists the creation functions with their boundaries, and presents the requested program with its output.
Result: np.random.randint creates the required array of five random integers.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(1)$ $\&$ $a\& b, a|b, a^b$
Key Points
NumPy Random
Use np.random.randint.
Upper bound is exclusive.
Q7a7MUnit 5 — Simple programs using the built-in functions of packages matplotlib
Core Concept
Construct a program to read cities.csv dataset, remove last column and save it in an array. Save the last column to another array. Plot the first two columns.
Answer:
import numpy as np
import matplotlib.pyplot as plt
data = np.genfromtxt('cities.csv', delimiter=',', skip_header=1, dtype=str)
features = np.array([[float(x) for x in row[:-1]] for row in data])
last = np.array([row[-1] for row in data])
plt.plot(features[:, 0], features[:, 1], marker='o')
plt.xlabel('First column'); plt.ylabel('Second column'); plt.show()
Tabular data with pandas. Pandas provides two structures. A Series is a one dimensional labelled array, and a DataFrame is a two dimensional table with labelled rows and columns. A DataFrame can be built from a dictionary of lists, from a list of dictionaries, from a NumPy array with column names, or by reading a file. The read csv function parses a delimited file into a DataFrame, and head, tail and sample inspect it. The shape, columns, index and dtypes attributes describe the structure, and describe summarises numeric columns with count, mean, standard deviation, minimum, quartiles and maximum. A column is selected with its name in square brackets, several columns with a list of names, and rows by label with loc or by position with iloc. Boolean indexing keeps the rows for which a condition is true. Missing values are found with isna and handled with dropna or fillna. The groupby method splits rows by a key and applies an aggregation, which is the basis of summarising marks per student or sales per region. Columns can be added by assignment, and mean with an axis argument computes a row average across selected columns. Merging joins two tables on a common key. A good answer explains the structures, the reading and inspection functions, selection and filtering, and then presents the requested program with its data and printed result.
Result: The last column is saved separately and the first two columns are plotted.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(n\log n)$ $O(1)$
Key Points
CSV and NumPy
Load CSV with genfromtxt.
Plot the first two numeric columns.
Q7b7MUnit 5 — Simple programs using the built-in functions of packages matplotlib
Core Concept
Explain the concept of DataFrame in pandas. Write a Python program to create a DataFrame from a dictionary and print it.
Answer: A DataFrame is a two-dimensional labelled data structure in pandas with rows and columns.
import pandas as pd
d = {'Name': ['Asha', 'Ravi'], 'Marks': [88, 72]}
df = pd.DataFrame(d)
print(df)
Tabular data with pandas. Pandas provides two structures. A Series is a one dimensional labelled array, and a DataFrame is a two dimensional table with labelled rows and columns. A DataFrame can be built from a dictionary of lists, from a list of dictionaries, from a NumPy array with column names, or by reading a file. The read csv function parses a delimited file into a DataFrame, and head, tail and sample inspect it. The shape, columns, index and dtypes attributes describe the structure, and describe summarises numeric columns with count, mean, standard deviation, minimum, quartiles and maximum. A column is selected with its name in square brackets, several columns with a list of names, and rows by label with loc or by position with iloc. Boolean indexing keeps the rows for which a condition is true. Missing values are found with isna and handled with dropna or fillna. The groupby method splits rows by a key and applies an aggregation, which is the basis of summarising marks per student or sales per region. Columns can be added by assignment, and mean with an axis argument computes a row average across selected columns. Merging joins two tables on a common key. A good answer explains the structures, the reading and inspection functions, selection and filtering, and then presents the requested program with its data and printed result.
Result: The dictionary becomes a DataFrame with Name and Marks columns.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.
Key Formula / Principle: $O(n\log n)$ $O(1)$
Key Points
DataFrame
Pandas DataFrame is a labelled table.
pd.DataFrame(dict) creates it.
Q7b7MUnit 5 — Tkinter examples
Core Concept
Design a calculator with the following buttons and functionalities like addition, subtraction, multiplication, division and clear.
Answer: A Tkinter calculator can keep the current expression in an Entry and append button text.
import tkinter as tk
root = tk.Tk()
e = tk.Entry(root, width=20); e.grid(row=0, column=0, columnspan=4)
def press(x):
e.insert(tk.END, x)
def clear():
e.delete(0, tk.END)
def equal():
try:
e.delete(0, tk.END); e.insert(0, str(eval(str(e.get()))))
except Exception:
e.delete(0, tk.END); e.insert(0, 'Error')
for i, t in enumerate(['7','8','9','/','4','5','6','*','1','2','3','-','C','0','=','+']):
cmd = clear if t == 'C' else equal if t == '=' else (lambda t=t: press(t))
tk.Button(root, text=t, command=cmd).grid(row=1 + i//4, column=i%4)
root.mainloop()
Graphical interfaces with Tkinter. Tkinter is the standard graphical toolkit that ships with Python. A program creates a root window with the Tk class, adds widgets to it and then enters the main loop, which waits for events and dispatches them to callbacks. Widgets include Label for text, Button for actions, Entry for single line input, Text for multi line text, Frame for grouping, Checkbutton and Radiobutton for choices, Listbox for selections, Scrollbar for navigation and Canvas for drawing. Geometry is controlled either by pack, which arranges widgets in blocks, or by grid, which places them in rows and columns, and both may be mixed only inside separate frames. A widget is given a callback through the command option for a simple action, or through the bind method, which associates an event pattern such as a mouse click or a key press with a handler. The handler receives an event object whose attributes report the position, the key and the widget. Values are read and written with the get and insert methods or with control variables of type StringVar. A good answer explains the root window, the widget set, geometry management, the difference between command and bind, and the role of mainloop, then presents the requested program with its layout and behaviour.
Result: The GUI supports digits, +, -, *, /, clear and equals.
Tip from Examiner: Define the concept, list the syntax or built-in functions used, walk through the program line by line with one sample input and its exact output, and close with the result or limitation.