Top Banner Ad
BCC302 · 2025-2642 Questions

Python Programming — 2025-26

Section A

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

What are Python variables? Give an example of declaring numeric data types.

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.
Q1a2MUnit 1 — Python variables
Survival ModePredictedRepeated

What are variables in Python?

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 — Understanding python blocks
Core Concept

What is a block in Python?

Answer: A block is a group of statements indented at the same level after a colon, as in if, else, for, while, def and class. Indentation, usually four spaces, defines the block boundary.
if x > 0: print('positive') Result: A Python block is a suite of indented statements controlled by a compound statement.

Key Points

  • Python Blocks
  • Defined by colon and consistent indentation.
  • Used by if, loops, functions and classes.
Q1b2MUnit 2 — Use of while loops in python
Survival ModePredictedRepeated

Differentiate between for loop using range and while loop in Python.

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.
Q1c2MUnit 2 — Use of while loops in python
Survival ModePredictedRepeated

What is a while loop in Python?

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.
Q1c2MUnit 3 — Using string data type and string operations
Survival ModePredictedRepeated

Explain string slicing in Python with an example.

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.
Q1d2MUnit 3 — Python Functions
Survival ModePredictedRepeated

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

What is a tuple in Python? How is it different from a list?

Answer: A list is mutable, ordered and written as [1, 2]; it can be changed with append() or item assignment. A tuple is immutable, ordered and written as (1, 2); its elements cannot be reassigned. Tuples are faster for fixed data and can be dictionary keys.\

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: Lists are changeable; tuples are fixed.

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 versus Tuple
  • List uses square brackets and is mutable.
  • Tuple uses parentheses and is immutable.
Q1e2MUnit 3 — Dictionary manipulation
Core Concept

Define dictionary in Python and give an example of its manipulation.

Answer: A dictionary stores data as key-value pairs in curly braces. d = {'roll': 1, 'name': 'Asha'} d['marks'] = 88 print(d.get('name')) print(d) This creates a dictionary, adds a key and reads a value.
Result: Dictionaries allow labelled access and easy manipulation by key.

Key Points

  • Dictionary
  • Stores key-value pairs.
  • Use key indexing or get() for access.
Q1e2MUnit 4 — write() and writelines() Manipulating file pointer using seek Programming
Core Concept

What is a file pointer in Python?

Answer: A file pointer is an internal marker that stores the current byte position where the next read or write will occur. It moves automatically as data is read or written and can be changed with seek().
Result: The file pointer tracks the current position in a file.

Key Points

  • File Pointer
  • Marks the next read/write position.
  • Changed with seek() and reported by tell().
Q1f2MUnit 4 — read()
Core Concept

What are read() and readline() functions in file handling?

Answer: read() reads the whole file or a given number of characters and returns one string. readline() reads only one line, including its trailing newline.
Result: read() returns full content; readline() returns the next single line.

Key Points

  • read() and readline()
  • read() reads all remaining content.
  • readline() reads one line per call.
Q1f2MUnit 5 — Python programming with IDE
Core Concept

What is an IDE in Python programming?

Answer: An IDE, Integrated Development Environment, is software that combines editing, running and debugging code in one place. Python IDEs include IDLE, PyCharm, VS Code and Jupyter. They provide syntax highlighting, autocomplete, error messages and an interactive console.
Result: An IDE helps write, run and debug Python programs efficiently.

Key Points

  • Python IDE
  • Combines editor, runner and debugger.
  • Examples: IDLE, PyCharm and VS Code.
Q1g2MUnit 5 — Tk Widgets
Core Concept

What are Tkinter widgets?

Answer: Tkinter widgets are the interactive components of a Tk GUI, such as Label, Button, Entry, Text, Frame, Checkbutton and Canvas.
Result: Widgets are the building blocks used to construct a Tkinter interface.

Key Points

  • Tkinter Widgets
  • Components such as buttons and labels.
  • They are placed with pack, grid or place.

Section B

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

Explain different types of basic operators in Python with 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.
Q2a7MUnit 1 — Python basic Operators
Survival ModePredictedRepeated

Explain Python basic operators and data types. Write a program to check if a number is even or odd using if-else.

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.
Q2b7MUnit 2 — if
Repeated

What are conditional statements in Python? Explain if, else, and elif with examples.

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.
Q2b7MUnit 2 — Loop manipulation using pass
Core Concept

Describe loop manipulation statements: pass, continue, break. Write a program to print prime numbers between 1 to 50 using for loop.

Concept / Given Data

The question asks for a description of the loop‑manipulation statements pass, continue, and break, and then to write a Python program that prints all prime numbers between 1 and 50 using a for loop. A prime number is an integer greater than 1 that has no positive divisors other than 1 and itself.

Key Formula / Principle: prime(n)  ⟺  ∀ d∈{2,…,n},  n mod d≠0\text{prime}(n) \iff \forall\, d\in\{2,\dots,\sqrt{n}\},\; n\bmod d \neq 0

Step‑by‑Step Solution

  1. pass – a null‑operation placeholder. It does nothing syntactically, allowing an empty block where a statement is required.
    for i in range(5):
        pass   # loop runs but body is intentionally empty
    
  2. continue – skips the remainder of the current iteration and proceeds with the next loop cycle.
    for i in range(1,6):
        if i % 2 == 0:
            continue   # even numbers are ignored
        print(i)
    
  3. break – terminates the innermost loop immediately, transferring control to the statement following the loop.
    for i in range(1,11):
        if i == 7:
            break   # loop stops when i reaches 7
        print(i)
    
  4. Prime‑number program – combine a for loop over the range 1 to 50 with an inner for loop that checks divisibility up to n\sqrt{n}. Use continue to skip non‑prime candidates and break to exit the inner loop as soon as a divisor is found.
    for n in range(2, 51):               # start from 2, the first prime
        is_prime = True
        for d in range(2, int(n**0.5) + 1):
            if n % d == 0:
                is_prime = False
                break                 # divisor found – not prime
        if is_prime:
            print(n, end=' ')
    
    The outer loop iterates 49 times; the inner loop runs at most 50≈7\sqrt{50}\approx7 times per candidate, making the algorithm efficient for this small range.

Result: The program outputs 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47, which are exactly the prime numbers between 1 and 50.

Tip from Examiner: Use **break** inside the divisor‑checking loop to avoid unnecessary iterations; a common mistake is to place **continue** after setting the flag, which would still print the number.

Key Points

  • pass is a null statement that does nothing
  • continue skips to the next iteration of the loop
  • break exits the innermost loop immediately
Q2c7MUnit 3 — String
Survival Mode

What are complex data types in Python? Explain strings, lists, tuples, and dictionaries with examples.

Answer: Complex data types hold collections of values. A string is a sequence of characters, for example s = 'abc'. A list is mutable and ordered, for example [1, 2]. A tuple is ordered but immutable, for example (1, 2). A dictionary stores key-value pairs, for example {'roll': 1, 'name': 'Asha'}.\

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: Strings, lists, tuples and dictionaries group related data in different structures.

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
  • str, list, tuple and dict hold collections.
  • Lists are mutable; tuples are immutable.
Q2c7MUnit 3 — Using string data type and string operations
Core Concept

Discuss string operations and built-in functions. Write a program to count vowels in a string.

Answer: String operations include indexing, slicing, concatenation, repetition and membership. Built-ins include len(), upper(), lower(), find(), count(), replace() and split(). s = input('String: ') vowels = 'aeiouAEIOU' print(sum(1 for ch in s if ch in vowels)) For 'Education' the vowel count is 5.\

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: The program counts vowels by testing each character against a vowel set.

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 Operations
  • Strings support slicing and built-in methods.
  • Count vowels with a generator and sum().
Q2d7MUnit 3 — String
Core Concept

Explain list and dictionary in-built functions. Write a program to merge two dictionaries.

Answer: List methods include append(), insert(), remove(), pop(), sort(), reverse(), count() and index(). Dictionary methods include keys(), values(), items(), get(), update(), pop() and clear(). d1 = {'a': 1, 'b': 2} d2 = {'b': 3, 'c': 4} d1.update(d2) print(d1) Output: {'a': 1, 'b': 3, 'c': 4}. Alternatively use merged = {**d1, **d2}.\

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: update() merges dictionaries with the second dictionary's values taking precedence.

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 and Dictionary Methods
  • List methods modify or search sequences.
  • dict.update() merges another dictionary.
Q2d7MUnit 4 — write() and writelines() Manipulating file pointer using seek Programming
Survival ModeRepeated

What is the purpose of the 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.
Q2e7MUnit 4 — write() and writelines() Manipulating file pointer using seek Programming
Core Concept

Describe file writing functions: write(), writelines(). Write a program to write student records to a file.

Answer: write() writes one string; writelines() writes a list of strings in one call. records = ['Asha,88 ', 'Ravi,72 '] with open('students.txt', 'w') as f: f.write('Name,Marks ') f.writelines(records)

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: write() handles a single string and writelines() writes all records from 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

  • File Writing
  • write() writes one string.
  • writelines() writes a sequence of strings.
Q2e7MUnit 5 — numpy
Core Concept

What are Python packages? Explain the purpose of packages like NumPy, Pandas, and Matplotlib.

Answer: Python packages are collections of modules that provide ready-made functions. NumPy supports fast arrays and numerical computation, Pandas supports table and CSV data analysis, and Matplotlib supports plots and charts. import numpy as np import pandas as pd import matplotlib.pyplot as plt

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 with specialised data, maths and visualisation tools.

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.
Three core packages and their roles NumPyarrays and maths Pandastables and csv Matplotlibcharts and plots import numpy as np, import pandas as pd, import matplotlib.pyplot as plt each package is a folder of modules installed once and imported by name they share data, so an array can feed a DataFrame and a plot
Key Formula / Principle: $O(n\log n)$ $O(1)$

Key Points

  • Python Packages
  • NumPy: numerical arrays.
  • Pandas: data tables; Matplotlib: visualisation.

Section C

7 Marks Each · 19 questions
Q3a7MUnit 1 — Python Data Types
Survival ModePredictedRepeated

What are Python data types? Explain numeric, string, and boolean data types.

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.
Q3a7MUnit 2 — else and else if
Core Concept

Explain Python blocks and conditional statements. Write a program to grade students based on marks using elif.

Answer: A Python block is a group of indented statements after a colon. Conditional statements use if, elif and else. m = int(input('Marks: ')) if m >= 90: grade = 'A' elif m >= 75: grade = 'B' elif m >= 60: grade = 'C' elif m >= 40: grade = 'D' else: grade = 'F' print('Grade:', grade)\

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: elif chains a grading decision and assigns one grade based on marks.

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

  • Blocks and Grading
  • Indentation defines the conditional block.
  • elif tests later ranges after earlier tests fail.
Q3b7MUnit 1 — Python variables
Core Concept

Write a Python program using variables and operators to calculate the sum of two numbers.

Answer: Variables store the inputs and the + operator computes the sum. a = int(input('Enter first number: ')) b = int(input('Enter second number: ')) s = a + b print('Sum =', s) For inputs 12 and 8 the output is Sum = 20.\

Variables, input and arithmetic. A variable in Python is a name bound to an object. Assignment uses a single equals sign, and the right hand side is evaluated first, so the name receives a reference to the resulting object. Names may contain letters, digits and underscores but cannot begin with a digit, and they are case sensitive. Python has no declaration statement and no type annotation requirement, although annotations may be added for documentation. Several names can be assigned in one statement, and two names can be swapped without a temporary variable. The input function always returns a string, so numeric input must be converted with int or float before arithmetic, otherwise the plus operator concatenates text instead of adding numbers. Arithmetic operators include addition, subtraction, multiplication, division, floor division, modulus and exponentiation. The print function writes values separated by spaces and accepts the end and separator arguments. A typical program reads two values, converts them, computes the result and prints a labelled output. A good answer explains the assignment model, lists the naming rules, shows the conversion from text to number, and then walks through the requested program line by line. It should state the sample input, the exact output and the type of each variable at the end. Mentioning that attempting arithmetic on unconverted input raises a TypeError shows practical awareness.

Result: The program reads two values into variables and prints their sum.

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

  • Variables and Operators
  • input() reads values.
  • The + operator adds numeric variables.
Q3b7MUnit 2 — string
Core Concept

Discuss for loops with strings and lists. Write a program to sum elements of a list.

Answer: A for loop can walk through characters of a string or elements of a list. for ch in 'abc': print(ch) nums = [1, 2, 3, 4] total = 0 for x in nums: total += x print('Sum =', total) Output sum is 10.\

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 strings and lists; adding each element gives the list sum.

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 with Strings and Lists
  • Strings yield characters.
  • Lists yield elements; use an accumulator for sum.
Q4a7MUnit 2 — Programming using Python conditional and loop blocks
Core Concept

Write a Python program to check whether a number is positive, negative, or zero using conditional blocks.

Answer: n = int(input('Enter a number: ')) if n > 0: print('positive') elif n < 0: print('negative') else: print('zero') The if branch tests positivity, elif tests negativity and else catches 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: Conditional blocks classify the number as positive, negative or zero.

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 Blocks
  • Use if, elif and else for mutually exclusive cases.
  • Exactly one branch executes.
Q4a7MUnit 3 — Python Functions
Core Concept

Explain functions in Python. Write a function to calculate area of circle.

Answer: A function is a named reusable block defined with def and called by name. It may take parameters and return a value. import math def area_circle(r): return math.pi * r * r print(area_circle(3)) For radius 3, area is about 28.27.\

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: Functions organise reusable code; area_circle returns the circle area.

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 Functions
  • def defines a function.
  • return sends the result back to the caller.
Q4b7MUnit 2 — Programming using Python conditional and loop blocks
Core Concept

Write a Python program using conditional statements and loops to print the multiplication table of a number.

Answer: n = int(input('Enter a number: ')) for i in range(1, 11): print(n, 'x', i, '=', n * i) The for loop repeats multiplication from 1 to 10 and prints each line.\

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: The program prints the multiplication table using a conditional-free for loop.

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

  • Loops
  • range(1, 11) gives multipliers 1 to 10.
  • Loop body prints product each iteration.
Q4b7MUnit 3 — string manipulation methods
Core Concept

Describe string manipulation methods. Write a program to replace characters in a string.

Answer: String manipulation methods return modified strings because strings are immutable. Common methods are lower(), upper(), strip(), replace(), split(), join(), find() and count(). s = 'Hello World' print(s.replace('l', 'L')) Output: HeLLo 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: replace() produces a new string with selected characters changed.

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 Methods
  • Strings are immutable.
  • replace() returns a modified copy.
Q5a7MUnit 1 — Python Data Types
Core Concept

Explain sets and their operations. Write a program to find difference between two sets.

Answer: A set is an unordered collection of unique values. Operations include union (|), intersection (&), difference (-), symmetric difference (^), add(), remove() and membership tests. Program to find difference: A = {1, 2, 3, 4} B = {3, 4, 5, 6} print('A-B:', A - B) print('B-A:', B - A) print('symmetric difference:', A ^ B) Output: A-B = {1, 2}, B-A = {5, 6}, symmetric difference = {1, 2, 5, 6}.\

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 difference removes elements found in the other set; symmetric difference keeps elements in only one set.

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

  • Sets and Operations
  • Sets store unique unordered values.
  • Use -, &, | and ^ for set algebra.
Q5a7MUnit 3 — Programming using string
Core Concept

Write a Python program demonstrating the use of in-built functions for strings, lists, and dictionaries.

Answer: Built-in functions work on strings, lists and dictionaries. s = 'Hello' print(len(s), s.upper(), s.lower()) L = [3, 1, 2] L.append(4); L.sort(); print(L) d = {'a': 1, 'b': 2} print(len(d), list(d.keys()), d.get('a')) This demonstrates length, case conversion, append, sort, keys and get.\

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: Built-ins reduce manual work for common string, list and dictionary tasks.

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

  • Built-in Functions
  • Strings: len, upper, lower.
  • Lists and dictionaries have append, sort, keys and get.
Q5b7MUnit 3 — Defining list and list slicing
Core Concept

Discuss tuple and list slicing. Write a program to reverse a tuple.

Answer: Both lists and tuples support slicing with start:stop:step. For t = (1, 2, 3, 4, 5), t[1:4] gives (2, 3, 4) and t[::-1] reverses it. t = (1, 2, 3, 4, 5) print(t[::-1]) Output: (5, 4, 3, 2, 1). Lists use the same syntax but return a list.\

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 works on both sequences; reversing uses a negative step.

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 and List Slicing
  • Slicing syntax is the same for both.
  • t[::-1] reverses a tuple.
Q5b7MUnit 3 — Use of Tuple data type
Core Concept

Differentiate between List and Tuple in Python with suitable examples.

Answer: A list is mutable, ordered and written as [1, 2]; it can be changed with append() or item assignment. A tuple is immutable, ordered and written as (1, 2); its elements cannot be reassigned. Tuples are faster for fixed data and can be dictionary keys.\

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: Lists are changeable; tuples are fixed.

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 versus Tuple
  • List uses square brackets and is mutable.
  • Tuple uses parentheses and is immutable.
Q6a7MUnit 4 — write() and writelines() Manipulating file pointer using seek Programming
Core Concept

Explain manipulating file pointer using seek(). Write a program to read last n lines from a file.

Answer: seek() moves the pointer. To read the last n lines efficiently, start near the end and count newlines. n = 3 with open('log.txt', 'rb') as f: f.seek(0, 2) size = f.tell() pos = max(0, size - 8192) f.seek(pos) lines = f.read().decode().splitlines()[-n:] print(' '.join(lines))

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(0, 2) goes to the end; reading a tail block and slicing gives the last n lines.

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 Pointer
  • seek(0, 2) moves to end of file.
  • tell() reports current byte position.
Q6a7MUnit 4 — using file operations
Core Concept

What are file operations in Python? Explain the different modes used while opening a file.

Answer: File operations are open, read, write, append, close, seek and tell. Opening modes include r for reading, w for writing, a for appending, r+ for read/write, w+ for write/read and binary variants rb, wb and ab.\

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: Python file operations create, inspect and update files under a chosen mode.

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 Operations
  • Open, read, write, append and close.
  • Modes r, w, a, + and b define access.
Q6b7MUnit 1 — Python Data Types
Core Concept

Describe regular expressions using re module. Write a program to find all digits in a string.

Answer: Regular expressions describe search patterns. Python's re module provides re.search(), re.findall(), re.match(), re.sub() and re.compile(). Example to find all digits in a string: import re s = 'A12 B3 C456' digits = re.findall(r'\d+', s) print(digits) Output: ['12', '3', '456'].\

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: re.findall with the digit pattern returns every digit group in the string.

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

  • Regular Expressions
  • re module supplies pattern matching functions.
  • re.findall(r'\d+', s) finds digit sequences.
Q6b7MUnit 4 — Writing files in python
Core Concept

Write a Python program to create a file and write multiple lines into it.

Answer: lines = ['First line ', 'Second line ', 'Third line '] with open('newfile.txt', 'w') as f: f.writelines(lines) with open('newfile.txt', 'r') as f: print(f.read())

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: Opening in w mode creates the file and writelines stores all lines.

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

  • Creating Files
  • w mode creates or truncates a file.
  • writelines writes multiple lines.
Q7a7MUnit 5 — Simple programs using the built-in functions of packages matplotlib
Survival ModePredictedRepeated

How is Matplotlib used in Python? Write a program to plot a simple line graph.

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.
Line graph of y equals two times x 12345 xy plt.plot joins the five points in order and plt.show displays the window
Key Formula / Principle: $O(n\log n)$ $O(1)$

Key Points

  • Matplotlib
  • Import matplotlib.pyplot as plt.
  • plot() draws; title and labels annotate.
Q7b7MUnit 5 — Tk Widgets
Core Concept

Discuss Tkinter widgets. Write a program to create a simple window with a label using Tkinter.

Answer: Tkinter widgets are GUI components such as Label, Button, Entry, Text, Frame, Checkbutton, Radiobutton, Listbox, Scrollbar and Canvas. import tkinter as tk root = tk.Tk() root.title('First Window') label = tk.Label(root, text='Hello Tkinter') label.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: Label displays text and mainloop starts the GUI event loop.

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

  • Tk Widgets
  • Widgets are GUI building blocks.
  • Label displays text; mainloop runs the window.
Q7b7MUnit 5 — GUI Programming: Tkinter introduction
Core Concept

What is Tkinter? Explain the role of Tkinter in GUI programming using Python.

Answer: Tkinter is Python's standard library toolkit for GUI programming. It provides windows, widgets and an event loop so programs can use buttons, labels, text fields and dialogs instead of only console input.\

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: Tkinter enables creation of desktop graphical interfaces 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

  • Tkinter
  • Standard Python GUI toolkit.
  • Provides widgets and event handling.