Top Banner Ad
BCC302 · 2024-2542 Questions

Python Programming — 2024-25

Section A

2 Marks Each · 13 questions
Q1a2MUnit 1 — Python variables
Survival ModePredictedRepeated

What are Python variables? Explain with examples.

Answer: A variable is a named location used to store a value that can be changed during program execution. In Python, assignment creates a variable automatically: x = 10, name = 'Asha'. Python variables are dynamically typed, so the same name can later hold another type.
Result: Variables store data under a name for later use.

Key Points

  • Python variables
  • A variable is a name bound to a value.
  • Created by assignment without type declaration.
Q1b2MUnit 1 — Python basic Operators
Survival ModePredictedRepeated

Describe Python basic operators with suitable examples.

Answer: Basic Python operators include arithmetic (+, -, *, /, //, %), comparison (==, !=, >, < ) and logical operators. Data types include int, float, str and bool. Program: n = int(input('Enter a number: ')) if n % 2 == 0: print(n, 'is even') else: print(n, 'is odd') The modulus operator gives the remainder; zero remainder means even.\

Operators in Python. An operator is a symbol that performs an operation on one or more values called operands, and the result is usually a new object. Arithmetic operators are addition, subtraction, multiplication, true division, floor division, modulus and exponentiation. Floor division discards the fractional part, while modulus returns the remainder, so together they let a program test divisibility. Comparison operators produce the Boolean values True or False and are the basis of every decision. Logical operators combine conditions and short circuit, so the second operand is evaluated only when the first does not decide the result. Assignment operators store a value in a name and the augmented forms combine an operation with assignment. Bitwise operators work on the binary representation of integers. Membership operators test whether a value occurs in a sequence, and identity operators test whether two names refer to the same object. Precedence and associativity decide the order of evaluation, and parentheses should be used when the intention is not obvious. Data types are the categories of values: integers, floating point numbers, complex numbers, strings, Booleans and the collection types. The type of a value decides which operators are legal and what they mean, which is why adding two numbers and adding a string to a number behave differently. A good answer groups the operators, gives one short example of each, shows the precedence order and then applies the relevant ones in the requested program with sample input and output.

Result: The program uses % and an if-else block to classify a number as even or odd.

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

  • Operators and Data Types
  • Arithmetic and comparison operators work with numeric types.
  • n % 2 == 0 tests evenness.
Q1b2MUnit 3 — Defining list and list slicing
Core Concept

What will be the output of the following Python code? def compute(x): return [i**2 for i in x if i%2==0] print(compute([1, 2, 3, 4, 5]))

Answer: The function keeps even numbers from the list and squares them. For [1, 2, 3, 4, 5], the even values are 2 and 4, so the output is [4, 16].
Result: Output: [4, 16].

Key Points

  • List Comprehension Output
  • Filter condition i % 2 == 0 keeps even values.
  • Squaring gives 4 and 16.
Q1c2MUnit 1 — Python Data Types
Survival ModePredictedRepeated

Explain different Python data types with examples.

Answer: Python data types classify values. Numeric types are int, float and complex, for example 5, 2.5 and 3+4j. A string is an ordered sequence of characters such as 'Hello' and supports indexing, slicing and concatenation. Boolean type has only True and False and results from comparisons. Other common types are list, tuple, dict and set.\

Python data types. Every value in Python is an object with a type, and the built-in function type reports that type at runtime. Numeric types include integers, which have unlimited precision, floating point numbers, which follow binary floating point rules, and complex numbers written with a real and imaginary part. The Boolean type has exactly two values, True and False, and it is a subclass of integer, which is why Booleans can appear in arithmetic. The string type holds an ordered, immutable sequence of characters and supports indexing, slicing, concatenation and a large family of methods. Collection types include lists, which are ordered and mutable, tuples, which are ordered and immutable, dictionaries, which map hashable keys to values, and sets, which hold unique unordered elements. The special value None represents the absence of a value and has its own type. Python converts between compatible types with int, float, str, bool and the collection constructors, and some operations convert implicitly, for example comparing an integer with a float. Immutable objects cannot be changed after creation, so operations on strings and tuples return new objects, while lists and dictionaries are modified in place. A good answer names each category, gives an example literal, states whether it is mutable, shows the result of type and explains one conversion. A small table with columns for type, example and mutability, followed by a program that prints each type, makes the answer complete.

Result: Numeric types store numbers, strings store text and boolean type stores logical truth values.

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

  • Python Data Types
  • int, float and complex form numeric types.
  • str holds text; bool holds True or False.
Q1c2MUnit 1 — Python basic Operators
Core Concept

Explain floor division with an example.

Answer: Floor division // divides and returns the largest integer less than or equal to the quotient. For example, 7 // 2 gives 3 and -7 // 2 gives -4. It discards the fractional part toward negative infinity.
Result: // returns the integer floor of a division result.

Key Points

  • Floor Division
  • 7 // 2 = 3.
  • Rounds down toward negative infinity.
Q1d2MUnit 1 — Python Data Types
Survival ModePredictedRepeated

How are numeric data types declared and used in Python?

Answer: Python data types classify values. Numeric types are int, float and complex, for example 5, 2.5 and 3+4j. A string is an ordered sequence of characters such as 'Hello' and supports indexing, slicing and concatenation. Boolean type has only True and False and results from comparisons. Other common types are list, tuple, dict and set.\

Python data types. Every value in Python is an object with a type, and the built-in function type reports that type at runtime. Numeric types include integers, which have unlimited precision, floating point numbers, which follow binary floating point rules, and complex numbers written with a real and imaginary part. The Boolean type has exactly two values, True and False, and it is a subclass of integer, which is why Booleans can appear in arithmetic. The string type holds an ordered, immutable sequence of characters and supports indexing, slicing, concatenation and a large family of methods. Collection types include lists, which are ordered and mutable, tuples, which are ordered and immutable, dictionaries, which map hashable keys to values, and sets, which hold unique unordered elements. The special value None represents the absence of a value and has its own type. Python converts between compatible types with int, float, str, bool and the collection constructors, and some operations convert implicitly, for example comparing an integer with a float. Immutable objects cannot be changed after creation, so operations on strings and tuples return new objects, while lists and dictionaries are modified in place. A good answer names each category, gives an example literal, states whether it is mutable, shows the result of type and explains one conversion. A small table with columns for type, example and mutability, followed by a program that prints each type, makes the answer complete.

Result: Numeric types store numbers, strings store text and boolean type stores logical truth values.

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

  • Python Data Types
  • int, float and complex form numeric types.
  • str holds text; bool holds True or False.
Q1d2MUnit 4 — Reading files
Survival ModePredicted

Describe the purpose of the 'with' statement in file handling.

Answer: The with statement is a context manager that opens a file and automatically closes it at the end of the block, even if an error occurs. Example: with open('a.txt') as f: data = f.read().
Result: with ensures safe resource handling and automatic closure.

Key Points

  • with Statement
  • Automatically closes files.
  • Recommended for file handling.
Q1e2MUnit 1 — Python Data Types
Core Concept

Write a Python program to demonstrate type casting between int, float, and string.

Answer: Type casting converts a value from one type to another using int(), float() and str(). x = int('25') y = float(x) z = str(y) print(x, y, z, type(x), type(y), type(z)) Output: 25 25.0 25.0 with types int, float and str.
Result: int(), float() and str() perform explicit type conversion.

Key Points

  • Type Casting
  • int() converts to integer.
  • float() and str() convert to float and string.
Q1e2MUnit 3 — Python Functions
Survival ModePredictedRepeated

Briefly describe the use of lambda functions in Python.

Answer: A function is a named block of reusable code defined with def. It can accept parameters, perform a task and return a result, avoiding repeated code.
Result: Functions make programs modular and reusable.

Key Points

  • Python Functions
  • Defined with def.
  • May take arguments and return values.
Q1f2MUnit 2 — if
Repeated

Explain the use of if, else, and elif. Write a Python program to check the given number is even or odd using if and else statement.

Answer: Conditional statements execute code depending on a test. if runs when its condition is true, else runs when it is false, and elif tests another condition after earlier ones fail. x = int(input('Number: ')) if x > 0: print('positive') elif x < 0: print('negative') else: print('zero')\

Conditional statements and blocks. A conditional statement chooses between alternative paths according to the truth value of a test. The if statement runs its block when the condition is true. The optional elif clause is tested only when all earlier conditions were false, and any number of elif clauses may follow. The optional else clause runs when no earlier condition was true, and it must come last. A block in Python is defined by indentation rather than braces, and every statement in a block must share the same indentation level, so consistent spaces are part of the syntax. Conditions are built from comparison operators and combined with and, or and not, which short circuit. Any object can be tested for truth: zero, empty strings, empty collections and None are false, and most other objects are true. Conditions may be nested, but a chain of elif is usually clearer. A conditional expression can choose between two values in a single line when the choice is simple. The order of the tests matters because the first true branch wins, so ranges should be checked from the most restrictive to the least. A good answer explains each keyword, shows the indentation rule, gives a small example with several branches, and then presents the requested program with a few sample inputs and their outputs. It should use elif rather than separate if statements when the cases are mutually exclusive.

Result: if, elif and else create mutually exclusive decision paths.

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

  • Conditional Statements
  • if checks the first condition.
  • elif adds further tests; else handles the remainder.
Q1f2MUnit 3 — Use of Tuple data type
Core Concept

Demonstrate how to assign a single value to a tuple.

Answer: A tuple with one value needs a trailing comma. t = (42,) print(t, type(t)) Without the comma, (42) is just an integer expression.
Result: Use (42,) to assign a single-element tuple.

Key Points

  • Single-value Tuple
  • Trailing comma is required.
  • (42) is not a tuple.
Q1g2MUnit 2 — Simple for loops in python
Core Concept

Differentiate between for loop and while loop with syntax and examples.

Answer: for loop syntax: for variable in iterable: block. Example: for i in range(3): print(i). It is used when iterations are known. while loop syntax: while condition: block. Example: i = 0; while i < 3: print(i); i += 1. It is used when repetition depends on a condition.
Result: for is sequence-based with a fixed iterable; while is condition-based and needs a state update.

Key Points

  • for versus while
  • for variable in iterable: suite.
  • while condition: suite with an update.
Q1g2MUnit 5 — numpy
Core Concept

Explain why numpy is used instead of python arrays for mathematical calculations.

Answer: NumPy arrays store values of one type in contiguous memory and support vectorised operations, so calculations are faster and require less code than Python lists. They also provide broadcasting, linear algebra, random generation and shape operations.
Result: NumPy is preferred for mathematical work because it is fast, compact and vectorised.

Key Points

  • NumPy Advantage
  • Contiguous homogeneous arrays.
  • Vectorised operations avoid slow Python loops.

Section B

7 Marks Each · 10 questions
Q2a7MUnit 1 — Python basic Operators
Predicted

Design a basic calculator in Python that supports addition, subtraction, multiplication, division.

Answer: A basic calculator can read two numbers and an operator and perform the chosen operation. a = float(input('First number: ')) b = float(input('Second number: ')) op = input('Operator (+ - * /): ') if op == '+': print(a + b) elif op == '-': print(a - b) elif op == '*': print(a * b) elif op == '/': print(a / b if b != 0 else 'division by zero not allowed') else: print('invalid operator')

Operators in Python. An operator is a symbol that performs an operation on one or more values called operands, and the result is usually a new object. Arithmetic operators are addition, subtraction, multiplication, true division, floor division, modulus and exponentiation. Floor division discards the fractional part, while modulus returns the remainder, so together they let a program test divisibility. Comparison operators produce the Boolean values True or False and are the basis of every decision. Logical operators combine conditions and short circuit, so the second operand is evaluated only when the first does not decide the result. Assignment operators store a value in a name and the augmented forms combine an operation with assignment. Bitwise operators work on the binary representation of integers. Membership operators test whether a value occurs in a sequence, and identity operators test whether two names refer to the same object. Precedence and associativity decide the order of evaluation, and parentheses should be used when the intention is not obvious. Data types are the categories of values: integers, floating point numbers, complex numbers, strings, Booleans and the collection types. The type of a value decides which operators are legal and what they mean, which is why adding two numbers and adding a string to a number behave differently. A good answer groups the operators, gives one short example of each, shows the precedence order and then applies the relevant ones in the requested program with sample input and output.

Result: The program supports addition, subtraction, multiplication and division with a zero-division guard.

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

  • Basic Calculator
  • Use arithmetic operators for calculation.
  • Check divisor before division.
Q2a7MUnit 2 — break and else
Core Concept

What are break, continue, and pass statements? Give code examples.

Concept / Given Data

The question requires a definition of the three loop‑control statements break, continue, and pass, followed by short Python code snippets that illustrate each statement’s effect inside a loop.

Key Formula / Principle: LoopControl  ∈{break,continue,pass}\text{LoopControl}\;\in\{\text{break},\text{continue},\text{pass}\}

Step‑by‑Step Explanation

  1. break – Immediately terminates the nearest enclosing loop. Control jumps to the first statement after the loop block.
    for i in range(1, 11):
        if i == 6:
            break               # stops the loop when i reaches 6
        print(i)
    # Output: 1 2 3 4 5
    
  2. continue – Skips the remaining statements in the current iteration and proceeds with the next iteration of the loop.
    for i in range(1, 6):
        if i % 2 == 0:
            continue            # even numbers are not printed
        print(i)
    # Output: 1 3 5
    
  3. pass – Does nothing; it is a syntactic placeholder that allows an empty block where a statement is required.
    for ch in "ABC":
        if ch == "B":
            pass                # no operation, loop continues normally
        print(ch)
    # Output: A B C
    
    Note: pass is especially useful when a block is intentionally left empty during development or when a statement is required by Python’s indentation rules.

Result: Each snippet demonstrates the distinct behaviour: break ends the loop early, continue jumps to the next iteration, and pass leaves the loop body unchanged.

Tip from Examiner: Remember that `else` attached to a loop runs only if the loop finishes without a `break`. Mis‑placing `break` can unintentionally suppress the `else` block.

A complete examination answer should define the concept, show the syntax or formula being used, and then walk through the program or calculation line by line. Naming each variable, stating a sample input and quoting the exact output makes the reasoning checkable. It also helps to mention one limitation or edge case, such as empty input, a missing key or division by zero, because that shows judgement rather than memory.

Key Points

  • break exits the loop immediately
  • continue skips the rest of the current iteration
  • pass is a placeholder that performs no action
Q2b7MUnit 1 — Python basic Operators
Predicted

Define Membership and Identity Operators. Given: a = 3, b = 3. Distinguish between: (a is b) and (a == b).

Answer: Membership operators test whether a value exists in a sequence: in and not in. Identity operators test whether two names refer to the same object: is and is not. For a = 3 and b = 3, both (a is b) and (a == b) are True in CPython because small integers are interned, but they mean different things: == compares values, is compares object identity.\

Membership and identity operators. Membership operators test whether a value occurs inside a container. The operator in returns True when the value is found and not in returns the opposite, and both work with strings, lists, tuples, dictionaries and sets. For a dictionary the test is against keys, and for a string it is a substring test. Identity operators test whether two names refer to the same object in memory. The operator is returns True only when both names point to the same object, and is not returns the opposite. The equality operator compares values, so two distinct objects that hold equal data are equal but not identical. The identity of an object can be inspected with the id function. Small integers and short strings are often interned by the interpreter, so two literals with the same value may happen to be the same object, which makes identity appear to work like equality in simple examples. This is an implementation detail and must not be relied on. The correct rule is to use equality for value comparison and to reserve identity for comparing with None, True and False, and for checking whether two names share a mutable object. A good answer defines both pairs, explains the difference between value and object identity, shows a short example with a list where two equal lists are not the same object, and illustrates why the small integer example is misleading. A note that membership scans a sequence but hashes for a set or dictionary shows awareness of cost.

Result: a == b tests equal values; a is b tests the same object, although both are True here.

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

  • Membership and Identity Operators
  • in tests membership in a sequence.
  • == compares value; is compares object identity.
Q2b7MUnit 2 — list and dictionaries
Core Concept

Write a Python program using for loop and dictionary to display student grades.

Answer: A dictionary stores grade boundaries and a for loop prints each student's grade. students = {'Asha': 88, 'Ravi': 72, 'Neha': 95} for name, marks in students.items(): if marks >= 90: grade = 'A' elif marks >= 75: grade = 'B' elif marks >= 60: grade = 'C' else: grade = 'D' print(name, marks, grade)

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: items() lets the loop access each name and mark, then conditional blocks assign grades.

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 and for loop
  • items() yields key-value pairs.
  • Conditional blocks decide grades.
Q2c7MUnit 2 — Programming using Python conditional and loop blocks
Predicted

Discuss the use of nested loops in Python. Write a program to print a right-angled triangle of stars.

Answer: Nested loops place one loop inside another. The outer loop controls rows and the inner loop controls columns. n = 5 for i in range(1, n + 1): for j in range(1, i + 1): print('*', end=' ') print() Output is a right-angled triangle of stars with row i containing i stars.\

Nested loops and printed patterns. A pattern is produced by controlling how many rows are printed and how many symbols each row contains. The outer loop counts rows, and the inner loop prints the characters for the current row. The print function ends each output with a newline by default; passing an empty string to the end argument keeps the cursor on the same line so a row is built from several calls. After the inner loop finishes, a bare print moves to the next line. The number of iterations in the inner loop may depend on the row number, which produces triangles, and it may depend on the total size minus the row number, which produces inverted shapes. A hollow shape prints a star at the first and last position of the row and spaces in between, with the first row holding a single star and the final row holding the full base. The count of spaces follows a formula such as twice the row index minus three. String multiplication gives a compact way to build a run of stars or spaces without an inner loop. Careful attention to the starting value of range avoids an off by one error, which is the most common mistake in these programs. A good answer explains the row and column control, shows the loop bounds, traces the first two and the last row, and then presents the program with its exact output.

Result: Nested loops generate two-dimensional patterns by controlling row and column counts.

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

  • Nested Loops
  • Outer loop handles rows.
  • Inner loop handles columns in each row.
Q2c7MUnit 3 — String
Predicted

Write a Python function to count the frequency of each character in a given string and return the output in a dictionary. Example: char_frequency("HELLO") returns {"H":1, "E":1, "L":2, "O":1}.

Answer: def char_frequency(s): freq = {} for ch in s: freq[ch] = freq.get(ch, 0) + 1 return freq print(char_frequency('HELLO')) Output: {'H': 1, 'E': 1, 'L': 2, 'O': 1}.\

Small string algorithms. Several classic exercises use only a loop over characters and a dictionary or a comparison. Counting the frequency of each character is done by creating an empty dictionary and, for each character, adding one to the stored count or to a default of zero. The get method with a default keeps the loop to a single line. The same pattern counts words, finds repeated characters and builds an index of positions. Finding the longest word in a list keeps one candidate and replaces it whenever a longer word appears; a strict comparison keeps the first word when two have the same length, which matches the stated requirement. Common letters between two strings are found by converting each string to a set and taking the intersection, then sorting the result so that the printed order is predictable. Case must be normalised first when the comparison should ignore case. Reading the input with the input function returns a string, and splitting on a separator converts it into a list of words; stripping each piece removes stray spaces. The output is usually rebuilt with join so that the separators are consistent. A good answer explains the algorithm in words, presents the function or program, and traces a sample input such as the word hello to show the dictionary that is produced. It should state the time cost and mention how ties and case are handled.

Result: The function counts each character in a dictionary using get() as a default.

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

  • Character Frequency
  • Use a dictionary as a counter.
  • get(ch, 0) handles the first occurrence.
Q2d7MUnit 3 — Using string data type and string operations
Survival ModePredictedRepeated

Explain string slicing and string operations in Python.

Answer: Slicing selects a substring using s[start:stop:step]; start is included, stop is excluded. For s = 'Python', s[1:4] gives 'yth' and s[::-1] gives 'nohtyP'. String operations include concatenation with +, repetition with *, membership with in, len(), upper(), lower(), strip(), replace(), split(), find() and count().\

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: Slicing extracts parts of a string and built-in methods transform or inspect 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(1)$ $\&$ $a\& b, a|b, a^b$

Key Points

  • String Slicing
  • s[start:stop:step] uses an exclusive stop.
  • String methods support search, case change and splitting.
Q2d7MUnit 4 — Reading files
Survival ModePredictedRepeated

Write a program to reverse the contents of a file character by character, separating each character with a comma.

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.
Q2e7MUnit 3 — Use of Tuple data type
Core Concept

Describe how tuples differ from lists in Python with examples.

Answer: Tuples use parentheses and cannot be modified; lists use square brackets and can be modified. For example, t = (1, 2) and L = [1, 2]. L[0] = 5 is valid, but t[0] = 5 raises TypeError.\

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.

Result: The core difference is immutability of tuples versus mutability of lists.

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

  • Tuples and Lists
  • Tuple: (1, 2), immutable.
  • List: [1, 2], mutable.
Q2e7MUnit 5 — Simple programs using the built-in functions of packages matplotlib
Predicted

Create a pie chart using matplotlib to represent the following data: Languages: Python, Java, C++, JavaScript, Ruby; Popularity: 30, 25, 20, 15, 10.

Answer: import matplotlib.pyplot as plt langs = ['Python', 'Java', 'C++', 'JavaScript', 'Ruby'] pop = [30, 25, 20, 15, 10] plt.pie(pop, labels=langs, autopct='%1.1f%%', startangle=90) plt.title('Language Popularity') plt.axis('equal') 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: pie() draws proportional slices and autopct shows percentages.

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.
Pie chart of language popularity Python 30 percent Java 25 percent C plus plus 20 percent JavaScript 15 percent Ruby 10 percent slice sizes are proportional to the given popularity values
Key Formula / Principle: $O(n\log n)$ $O(1)$

Key Points

  • Pie Chart
  • Use plt.pie with labels and values.
  • autopct displays percentages.

Section C

7 Marks Each · 19 questions
Q3a7MUnit 1 — Understanding python blocks
Core Concept

Write short notes on the following with examples: a) Operator Precedence b) Python Indentation c) Type Conversion

Short Notes (7 marks)

a) Operator Precedence

Operator precedence determines the order in which Python evaluates expressions. The hierarchy (from highest to lowest) is:

  1. Parentheses () – force evaluation first.
  2. Exponentiation ** – right‑associative.
  3. Unary plus/minus +x, -x and bitwise NOT ~.
  4. Multiplication, division, floor‑division, modulo *, /, //, %.
  5. Addition and subtraction +, -.
  6. Bitwise shifts &lt; &lt; , >>.
  7. Bitwise AND &.
  8. Bitwise XOR ^.
  9. Bitwise OR |.
  10. Comparison operators ==, !=, &lt; , &lt; =, >, >=, is, is not, in, not in.
  11. Logical NOT not.
  12. Logical AND and.
  13. Logical OR or.
  14. Assignment =, +=, -=, *=, /=, %=, //=, **=, &=, ^=, |=, &lt; &lt; =, >>=.

Example: 3 + 4 * 2 ** 3 evaluates as 3 + 4 * 8 = 35 because ** > * > +.

b) Python Indentation

Python uses indentation to delimit blocks instead of braces. The rules are:

  1. A block starts with a colon : after a statement (e.g., if, for).
  2. All statements in the block must be indented by the same amount (typically 4 spaces).
  3. Indentation must be consistent; mixing tabs and spaces is disallowed.
  4. A block ends when the indentation level decreases.

Example:

if x > 0:
    print("Positive")
    if x > 10:
        print("Large")
print("Done")

Here the inner print("Large") is indented twice, indicating it belongs to the inner if.

c) Type Conversion

Python supports implicit (automatic) and explicit (manual) type conversion.

  • Implicit conversion occurs in mixed‑type arithmetic: int + float → float, int + complex → complex.
  • Explicit conversion uses built‑in constructors: int(), float(), str(), bool(), list(), tuple(), set(), dict().

Example:

x = 5          # int
y = 2.5        # float
z = x + y      # z is float 7.5
w = int(y)     # w is int 2
s = str(x)     # s is string "5"

Type conversion is essential when reading input (always strings) and when performing operations that require a specific type.

Result: Understanding operator precedence, indentation, and type conversion is fundamental for writing correct, readable Python code.

Tip from Examiner: For 7‑mark questions, structure your answer with a brief definition, a clear rule list, and a concise example. Avoid long code blocks; use inline snippets. Remember to use $...$ for any mathematical notation.
Key Formula / Principle: $O(1)$ $\&$ $a\& b, a|b, a^b$

Key Points

  • Operator precedence hierarchy
  • Indentation defines blocks
  • Implicit vs explicit type conversion
Q3a7MUnit 3 — Dictionary manipulation
Core Concept

Write a program to demonstrate Create, Read, Update, and Delete (CRUD) operations on a dictionary.

Answer: CRUD means create, read, update and delete. d = {} d['name'] = 'Asha' # create print(d['name']) # read d['name'] = 'Ravi' # update del d['name'] # delete print(d)

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: Dictionary items are created or updated by assignment, read by key and deleted with del or pop().

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 CRUD
  • Assignment creates or updates keys.
  • del or pop removes a key.
Q3b7MUnit 3 — string manipulation methods
Core Concept

Explain commonly used string methods in Python. Write a program using the following operations on the given string: text="Machine Learning"\text{text} = \text{"Machine Learning"}. Use the following methods: • lower()\text{lower}() • upper()\text{upper}() • strip()\text{strip}() • replace()\text{replace}() • find()\text{find}() • count()\text{count}()

Answer: text = ' Machine Learning ' print(text.lower()) # machine learning print(text.upper()) # MACHINE LEARNING print(text.strip()) # Machine Learning print(text.replace('Learning', 'AI')) # Machine AI print(text.find('Learning')) # 9 print(text.count('e')) # 3

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: These methods change case, remove outer spaces, replace text, locate substrings and count occurrences.

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 String Methods
  • lower/upper change case.
  • strip, replace, find and count inspect or transform text.
Q4a7MUnit 2 — Programming using Python conditional and loop blocks
Predicted

Write a program to create a hollow pyramid pattern given below: *

  • *
  • *
    

Answer: The pattern has a blank line for each slanted side and a full star base. n = 5 for i in range(1, n): if i == 1: print('') else: print('' + ' ' * (2 * i - 3) + '') print('' * (2 * n - 1)) For n = 5 this prints *, * space *, * three spaces *, * five spaces *, then nine stars.\

Nested loops and printed patterns. A pattern is produced by controlling how many rows are printed and how many symbols each row contains. The outer loop counts rows, and the inner loop prints the characters for the current row. The print function ends each output with a newline by default; passing an empty string to the end argument keeps the cursor on the same line so a row is built from several calls. After the inner loop finishes, a bare print moves to the next line. The number of iterations in the inner loop may depend on the row number, which produces triangles, and it may depend on the total size minus the row number, which produces inverted shapes. A hollow shape prints a star at the first and last position of the row and spaces in between, with the first row holding a single star and the final row holding the full base. The count of spaces follows a formula such as twice the row index minus three. String multiplication gives a compact way to build a run of stars or spaces without an inner loop. Careful attention to the starting value of range avoids an off by one error, which is the most common mistake in these programs. A good answer explains the row and column control, shows the loop bounds, traces the first two and the last row, and then presents the program with its exact output.

Result: Conditional spacing inside a loop produces the hollow pyramid and its solid base.

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

  • Pattern Printing
  • Use increasing spaces between two stars.
  • Print 2*n-1 stars for the base.
Q4a7MUnit 3 — List and Dictionary
Core Concept

How can data be organized using complex data types in Python?

Answer: Complex data types organise related values: lists store ordered mutable sequences, tuples store fixed ordered records, dictionaries store labelled key-value data and sets store unique values. For example, a student can be stored as {'name': 'Asha', 'marks': [80, 85]} and many students in a list of dictionaries.\

Organising data with collection types. Python offers four general purpose collections and each answers a different question. A list is an ordered mutable sequence used when the position matters and the contents change. A tuple is an ordered immutable sequence used for a fixed record whose fields will not change. A dictionary is a mapping from hashable keys to values and is used when each item has a name or identifier. A set stores unique elements without order and is used for membership tests and for removing duplicates. These types nest freely, so a realistic record can combine them. A student may be represented by a dictionary with a name, a roll number and a list of marks, and a class is then a list of such dictionaries. A tuple could hold a fixed pair such as a latitude and longitude, and a set could hold the subjects a student has chosen. Choosing the correct type makes the code shorter and faster: a dictionary lookup is constant time whereas a search through a list is linear, and a set prevents duplicates automatically whereas a list does not. Iteration, length, membership and comprehensions work across all of them. A good answer describes each type with its syntax and mutability, shows one small example of each, and then builds the requested structure, explaining why each level of the nesting was chosen.

Result: Lists, tuples, dictionaries and sets group data for structured processing.

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

  • Complex Data Types
  • Lists and tuples hold sequences.
  • Dictionaries label values; sets remove duplicates.
Q4b7MUnit 2 — Use of while loops in python
Core Concept

Explain why loops are needed and the types of loops in python. Discuss break and continue with example.

Answer: Loops avoid repetition and allow a block to run many times. Python has for loops for iterating sequences and while loops for condition-based repetition. break exits the loop immediately; continue skips the current iteration and moves to the next. for i in range(1, 6): if i == 3: break print(i) for i in range(1, 6): if i == 3: continue print(i) The first prints 1, 2; the second prints 1, 2, 4, 5.\

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: Loops repeat work; break stops the loop and continue skips one turn.

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

  • Loop Control
  • for iterates; while tests a condition.
  • break exits; continue skips current iteration.
Q4b7MUnit 4 — Reading files
Core Concept

Explain file handling modes in Python.

Answer: Common file modes are r (read), w (write and truncate), a (append), r+ (read and write), w+ (write and read), a+ (append and read) and binary variants rb, wb, ab. Modes may add b for binary or t for text.\

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: The mode decides whether a file can be read, written, appended or combined.

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 Modes
  • r reads; w writes; a appends.
    • allows both reading and writing.
Q5a7MUnit 3 — String
Core Concept

Write a function to find the longest word in a given list of words. Example: longest_word(['apple', 'banana', 'cherry']) returns 'banana'.

Answer: def longest_word(words): longest = '' for w in words: if len(w) > len(longest): longest = w return longest print(longest_word(['apple', 'banana', 'cherry'])) Output: banana.\

Small string algorithms. Several classic exercises use only a loop over characters and a dictionary or a comparison. Counting the frequency of each character is done by creating an empty dictionary and, for each character, adding one to the stored count or to a default of zero. The get method with a default keeps the loop to a single line. The same pattern counts words, finds repeated characters and builds an index of positions. Finding the longest word in a list keeps one candidate and replaces it whenever a longer word appears; a strict comparison keeps the first word when two have the same length, which matches the stated requirement. Common letters between two strings are found by converting each string to a set and taking the intersection, then sorting the result so that the printed order is predictable. Case must be normalised first when the comparison should ignore case. Reading the input with the input function returns a string, and splitting on a separator converts it into a list of words; stripping each piece removes stray spaces. The output is usually rebuilt with join so that the separators are consistent. A good answer explains the algorithm in words, presents the function or program, and traces a sample input such as the word hello to show the dictionary that is produced. It should state the time cost and mention how ties and case are handled.

Result: The function compares word lengths and returns the longest word.

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

  • Longest Word
  • Track the longest string seen.
  • Compare using len().
Q5a7MUnit 4 — Reading files
Core Concept

Write a program to read and write data from a text file. How do readline()\text{readline}() and readlines()\text{readlines}() work? Explain with examples.

Answer: with open('data.txt', 'w') as f: f.write('Hello Python') with open('data.txt', 'r') as f: print(f.readline()) # Hello print(f.readlines()) # ['Python'] readline() returns one line including its newline. readlines() returns a list of all remaining lines.\

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: readline() reads one line; readlines() reads all lines into a 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

  • Reading and Writing
  • write() stores text.
  • readline gives one line; readlines gives a list.
Q5b7MUnit 3 — Dictionary manipulation
Core Concept

Distinguish between a Tuple and a List with examples. Explain with examples at least 4 built-in methods of Dictionary.

Answer: A tuple is immutable and written (1, 2); a list is mutable and written [1, 2]. Four dictionary methods are: keys() returns keys, values() returns values, items() returns key-value pairs and get() returns a value safely. d = {'a': 1, 'b': 2} print(list(d.keys()), list(d.values()), list(d.items()), d.get('a'))\

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: Tuples differ by immutability; dictionaries provide methods for keys, values, pairs and safe lookup.

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, List and Dictionary
  • Tuple immutable; list mutable.
  • keys, values, items and get are dictionary methods.
Q5b7MUnit 4 — write() and writelines() Manipulating file pointer using seek Programming
Survival ModeRepeated

What is the purpose of the seek()\text{seek}() method in file handling? Demonstrate a program that copies content from one file to another.

Answer: seek(offset, whence) moves the file pointer to a byte position. whence 0 is from the beginning, 1 from current position and 2 from the end. seek(0) rewinds a file. Example copy program: with open('source.txt', 'r') as src, open('copy.txt', 'w') as dst: for line in src: dst.write(line) with open('copy.txt', 'r') as f: print(f.read())

File pointers and seek. Every open file has a pointer that records the position of the next read or write in bytes from the start. The tell method returns the current pointer position. The seek method moves the pointer and takes an offset and an optional reference point called whence. A whence of zero measures from the beginning, one from the current position and two from the end, and text mode restricts the offsets that are allowed. Moving to zero rewinds the file, and moving to zero with whence two jumps to the end, which is useful for appending or for finding the size. Reading the last lines of a file without scanning the whole file starts from a position near the end, reads the remaining bytes, decodes the text and keeps only the final lines. This requires binary mode because arbitrary byte offsets are permitted there. Copying a file reads a block and writes it to the destination, and the pointer of each file advances independently, so seeks are needed when a block must be revisited. Writing after reading without a seek overwrites at the current position. A good answer defines the pointer, explains the three reference points, gives a small example with tell before and after a seek, and then presents the requested program with its input file and result. It should mention that the file must be flushed or closed before another program reads it.

Result: seek() controls the read/write position; the program copies text line by line.

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

  • seek() and File Copy
  • seek(offset, whence) repositions the pointer.
  • Read from source and write to destination.
Q6a7MUnit 4 — Writing files in python
Predicted

Discuss different types of file modes in Python? Explain with examples.

Answer: r reads only, w writes and truncates, a appends, r+ reads and writes without truncating, w+ writes and reads with truncation, a+ appends and reads. Binary modes rb, wb and ab handle bytes. For example, open('x.txt', 'a') adds text at the end.\

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: File modes specify permitted operations and whether existing content is kept.

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 Opening Modes
  • r, w and a are basic modes.
    • adds reading/writing; b selects binary.
Q6a7MUnit 5 — Simple programs using the built-in functions of packages matplotlib
Core Concept

Write a Python program using numpy to perform matrix operations.

Answer: NumPy arrays support fast element-wise matrix operations. import numpy as np A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) print('Add: ', A + B) print('Multiply elementwise: ', A * B) print('Matrix product: ', A @ B) print('Transpose: ', A.T) print('Determinant:', np.linalg.det(A))

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: + and * work elementwise, @ gives matrix product and linalg handles linear algebra.

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.
Matrix addition and matrix product 1 23 4A 5 67 8B 6 810 12A plus B 19 2243 50A at B plus and star work element by element the at operator gives the matrix product
Key Formula / Principle: $O(1)$ $\&$ $a\& b, a|b, a^b$

Key Points

  • NumPy Matrix Operations
  • Arrays support elementwise arithmetic.
  • A @ B is the matrix product.
Q6b7MUnit 5 — Simple programs using the built-in functions of packages matplotlib
Core Concept

Explain the use of matplotlib for data visualization. Write a program to visualize Line plots using these data: x = [1, 2, 3, 4, 5], y = [10, 20, 25, 30, 40]

Answer: Matplotlib turns data into charts for quick interpretation. import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [10, 20, 25, 30, 40] plt.plot(x, y, color='green', marker='o') plt.title('Line Plot') plt.xlabel('x') plt.ylabel('y') plt.grid(True) 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 visualises y against x as a labelled line plot.

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.
Line plot of y against x 12345 4020 title, axis labels and grid make the trend readable
Key Formula / Principle: $O(n\log n)$ $O(1)$

Key Points

  • Line Plots
  • plot(x, y) draws the relationship.
  • Labels, grid and markers improve readability.
Q6b7MUnit 5 — pandas etc
Core Concept

Write a program to read a CSV file and display the rows where a specific column value exceeds a given threshold.

Answer: import pandas as pd df = pd.read_csv('data.csv') col = input('Column name: ') threshold = float(input('Threshold: ')) print(df[df[col] > threshold])

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: Boolean indexing displays rows whose chosen column exceeds the threshold.

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 Filtering
  • read_csv loads the file.
  • df[df[col] > threshold] filters rows.
Q7a7MUnit 5 — Tk Widgets
Survival Mode

Discuss the role of event handling in Tkinter. How can you bind events to widgets? Provide examples.

Answer: Event handling lets a GUI respond to user actions such as clicks and key presses. Tkinter uses widget.bind(event, handler), where the handler receives the event object. import tkinter as tk root = tk.Tk() b = tk.Button(root, text='Click') def show(e): print('Button clicked at', e.x, e.y) b.bind('< Button-1>', show) b.pack(); root.mainloop() Buttons also use the command option for simple click handling.\

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: bind() connects an event pattern to a callback function.

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

  • Tkinter Events
  • bind(event, handler) attaches events.
  • command is simpler for button clicks.
Q7a7MUnit 5 — GUI Programming: Tkinter introduction
Core Concept

What is GUI programming in Python? Write a GUI-based Python program using Tkinter to accept and display student data.

Answer: GUI programming builds applications with windows and controls. The program below accepts student data and displays it. import tkinter as tk root = tk.Tk() tk.Label(root, text='Name').pack() name = tk.Entry(root); name.pack() tk.Label(root, text='Roll').pack() roll = tk.Entry(root); roll.pack() out = tk.Label(root, text=''); out.pack() def show(): out.config(text='Student: ' + name.get() + ' Roll: ' + roll.get()) tk.Button(root, text='Submit', command=show).pack() 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: Entry widgets collect data and the button handler displays it in a Label.

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

  • GUI Student Form
  • Entry collects input.
  • Button command updates the display label.
Q7b7MUnit 5 — Simple programs using the built-in functions of packages matplotlib
Core Concept

How do we use packages in Python programming? Explain the use of pandas.

Answer: Packages are folders of modules installed with pip and imported by name. Pandas is used for data handling through Series and DataFrame; it reads CSV and Excel files, cleans data, selects rows and columns, groups data and computes statistics. import pandas as pd df = pd.read_csv('data.csv') print(df.head()) print(df.describe())

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: Packages extend Python and pandas provides tabular data analysis.

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.
From csv file to DataFrame to summary statistics data.csvrows of text DataFramenamed columnsone dtype per column describemean and spreadhead shows rows read csv parses the file, head and tail inspect it dtypes, shape and describe answer most first questions columns can then be selected, filtered or grouped
Key Formula / Principle: $O(n\log n)$ $O(1)$

Key Points

  • Packages and Pandas
  • Install packages and import them.
  • Pandas handles DataFrames and CSV data.
Q7b7MUnit 5 — pandas etc
Core Concept

Write a program to read data from a CSV file 'students.csv', calculate the average marks for each student, and display the results.

Answer: import pandas as pd df = pd.read_csv('students.csv') marks = [c for c in df.columns if 'mark' in c.lower()] df['average'] = df[marks].mean(axis=1) print(df[['name'] + marks + ['average']] if 'name' in df else 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 program reads the CSV and adds an average column computed across mark 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

  • Average Marks
  • read_csv loads student records.
  • mean(axis=1) averages each row.