Exam Answer Book

Audio version created with Paper2Audio.

Listen on Paper2Audio

Complete solutions for all 60 questions

Unit 1: Introduction to Python Programming Unit 2: Python Operators and Control Flow Statements

Designed for 20-mark preparation

35 theory answers and 25 programming solutions, in the same unit and category order as the supplied question bank. Each answer is self-contained, with definitions, explanatory points, examples and exam-relevant cautions.

How to use the theory answers

Suggested 20-mark structure: definition and context, core explanation and distinctions, example with output and interpretation, concluding point or limitation. These are preparation allocations, not an official marking scheme.

How to use the programming answers

Suggested 20-mark structure: problem definition and assumptions, algorithm (4), correct program, sample output and dry run, edge cases and complexity. Explain the logic in your own words as well as writing the code.

Conventions

All runnable code uses Python 3.7+ language features. Python 2 is discussed only for the comparison question. Except where validation is shown, programs assume input has the requested numeric form.

Printed outputs omit interactive prompts; sample input is listed separately. Long output sequences may wrap on the page.

Scope and checking

Source: Python Questions.pdf, 7 pages. All 60 code examples were executed and their displayed outputs checked, with 54 additional boundary checks for the programming solutions. Question labels such as U.1-T.0.1 and U.2-P.0.1 distinguish repeated numbering.

Use the question indexes on the next two pages to locate any answer. P.D.F bookmarks also link directly to each question.

Unit 1 - question index

Unit 2 - question index

U.1-T.0.1 | Theory | 20-Mark Preparation

What is Python? Explain any five features.

Python is a high-level, general-purpose programming language created by Guido van Rossum. It allows programmers to express algorithms using readable statements and indentation. Python supports procedural, object-oriented and functional styles and is widely used for scripts as well as large applications.

Key explanation

1. Simple and readable. Python uses clear keywords and indentation to group statements. A beginner can express input, processing and output with relatively little syntax. Readability reduces the effort needed to maintain a program.

2. High-level and interpreted. Python provides abstractions such as lists and dictionaries, so programmers rarely manage memory directly. A Python implementation executes the program; Sipai-thon normally compiles source to bytecode and then executes that bytecode. Interpreted does not mean that no compilation ever occurs.

3. Dynamically typed. Names do not require an explicit type declaration. At runtime, a name refers to an object that has a type, and the name may later refer to a different type of object.

4. Portable. The same source code can often run on different operating systems when a compatible interpreter and required libraries are available. Operating-system-specific operations may still need adjustment.

5. Rich library support. The standard library supplies modules for mathematics, files, dates and networking. Additional packages extend Python to scientific computing, web applications and other fields.

Python 3 code / example

: Code summary: This procedure calculates the average score from a list of marks for a specific student and prints a success message if that average meets the minimum passing threshold of 50.

Expected output

Anu passed with 85.0

Explanation of the example

The example combines readable assignment, a built-in list, automatic numeric typing and indentation. sum() and len() supply useful operations without writing their algorithms. The colon introduces a block, and the indented print statement runs only when the condition is true.

Python emphasizes programmer productivity. Its readable syntax and libraries are strengths; execution speed can be lower than that of native compiled code for some C.P.U-intensive work.

U.1-T.0.2 | Theory | 20-Mark Preparation

Explain any five real-world applications of Python.

Python is a general-purpose language: the same basic concepts of variables, collections, functions and control flow can solve problems in many domains. Libraries provide specialized capabilities while Python coordinates the steps.

Key explanation

1. Web development. Server-side applications receive requests, validate data, interact with databases and return responses. Django and Flask are examples of Python frameworks. An online bookstore may use Python to process searches and orders.

2. Data analysis and visualization. Python can clean tabular data, calculate summaries and create charts. pandas and Matplotlib are examples of relevant libraries. A business can analyze monthly sales and compare product performance.

3. Artificial intelligence and machine learning. Python is used to prepare training data, fit statistical models and evaluate predictions. Scikit-learn and PyTorch are example libraries. Applications include spam detection and image classification.

4. Automation and scripting. Scripts automate repetitive file, text and administrative tasks. Standard-library modules such as pathlib and csv help process folders and reports. A script can combine daily data files into one report.

5. Scientific and numerical computing. Python is used in simulations, numerical methods and engineering calculations. NumPy and SciPy are examples of scientific libraries. Researchers can analyze experimental readings and solve numerical problems.

Python 3 code / example

Code summary: This procedure calculates the total and average of a list of sales figures. It first aggregates the sum of all sales and then divides that total by the number of entries to determine the mean value, outputting both results.

Expected output

Total: 5600

Average: 1400.0

Explanation of the example

This small data-analysis example stores four sales values, computes their total and divides by the number of observations. In a real application, the values could be read from a C.S.V file or database. Domain libraries build on the same input-process-output model.

Python is useful across domains because readable code combines with reusable libraries. The application determines which libraries, data sources and performance requirements are appropriate.

U.1-T.0.3 | Theory | 20-Mark Preparation

Differentiate between Python 2 and Python 3 with examples.

Python 2 and Python 3 are major language versions with some incompatible syntax and behavior. Python 2 reached end of life in 2020. Use Python 3 for the programs in this answer book; Python 2 examples below are historical comparisons.

Key explanation

1. Printing. Python 2 commonly uses the print statement: print "Hello". Python 3 uses the print() function: print("Hello"). Function syntax supports named arguments such as end and sep.

2. Integer division. In Python 2, 5 / 2 gives 2 when both operands are integers, unless true division is enabled. In Python 3, 5 / 2 gives 2.5. In both versions, 5 // 2 gives 2. Floor division rounds down, not simply toward zero.

3. Text and bytes. Python 2 distinguishes str byte strings from unicode text. Python 3 uses str for Unicode text and bytes for binary data. Conversion between text and bytes requires an encoding or decoding operation.

4. Keyboard input. Python 2 raw input() returns text; its input() evaluates an expression. Python 3 input() returns text. Numeric input is explicitly converted, for example int(input("Number: ")).

5. Iteration and mapping views. Python 2 range() creates a list, while xrange() provides a lazy sequence-like object. Python 3 range() is a compact immutable sequence. Python 3 dictionary keys(), values() and items() return views instead of Python 2 lists.

6. Migration impact. Some old code must be changed, not merely run with a newer interpreter. Check print syntax, division, input, text encoding and A.P.I's when translating historical examples.

Python 3 code / example

Code summary: This Python script demonstrates basic arithmetic and data type operations by calculating a floating-point division and an integer floor division of 5 by 2, generating a list of integers from 0 to 2 using a range, and retrieving the class name of a string variable.

Expected output

Code summary: This snippet demonstrates a sequence of diverse data types, including a floating-point number, an integer, a list of integers, and a string, likely used to illustrate type variation or test a generic data handler.

Explanation of the example

The division results demonstrate the most common numerical difference. list (range(3)) explicitly materializes the compact range as a list. A normal quoted string is Unicode text in Python 3. Do not execute Python 2 print-statement syntax in a Python 3 answer.

Python 3 improves consistency in printing, division and text handling. State both sides of each difference and give a small example to make a comparison answer complete.

U.1-T.0.4 | Theory | 20-Mark Preparation

State the rules for naming a variable, with valid and invalid names.

A variable name is an identifier used to refer to an object. The assignment statement binds the name to a value, for example total = 100. Python distinguishes the legal syntax of an identifier from recommended naming style.

Key explanation

1. Allowed characters and first character. For ordinary ascii names, use letters A-Z or a-z, digits and underscores. The first character must be a letter or underscore; a digit may appear after it. Python also allows many Unicode letters, but simple ascii names are easiest to write in an exam.

2. Case sensitivity. Names are case-sensitive: marks, Marks and Marks are three different identifiers. Use consistent case to avoid accidental references to a different name.

3. No keywords. Reserved words such as if, for, class and return cannot be ordinary variable names. Python needs them to express language structure.

4. No spaces or punctuation. student name is invalid because it contains a space. student-name is parsed as subtraction, not one identifier. Names such as total@ and price% are invalid identifiers.

5. Valid examples. age, student name, marks2 and _count are valid. 2marks is invalid because it begins with a digit. class is invalid because it is a keyword. There is no need to declare a type before assignment.

6. Style versus legality. Use descriptive snake case names such as total marks. A name such as list is legal but shadows a built-in and should normally be avoided. Upper Case is a convention for constants, not an enforcement mechanism.

Python 3 code / example

Code summary: This script demonstrates basic variable assignment and case sensitivity in Python by storing a student's name, age, and multiple mark values, then printing a subset of these variables to the console to show how distinct variable names, including those with different casing, are handled independently.

Expected output

Ravi 18

80 90

Explanation of the example

The first four assignments use valid identifiers. Marks and marks coexist because capitalization matters. An invalid identifier usually causes a SyntaxError before normal execution begins; a valid but undefined name causes a NameError when evaluated.

A good name must first obey identifier rules and should then communicate its purpose. Legal names are not automatically clear or good style.

U.1-T.0.5 | Theory | 20-Mark Preparation

Explain how Python determines the type of a value without a declaration.

Python uses dynamic typing. Objects have types, while variable names are references to objects. When an expression is evaluated, Python creates or obtains an object with a type and binds the target name to that object. The programmer does not declare a permanent type for the name.

Key explanation

1. Assignment establishes a binding. In x = 10, the integer literal produces an int object and x refers to it. In x = "ten", x is rebound to a str object. The original integer does not change into a string.

2. Literals and expressions determine types. 10 is int, 10.5 is float, "10" is str and True is bool. An expression can produce a different type: 5 / 2 produces the float 2.5 in Python 3.

3. Types are checked during execution. Operations depend on the types of the objects involved. Numeric addition and string concatenation both use +, but "5" + 2 is invalid and raises TypeError.

4. Input and explicit conversion. input() returns str even when digits are entered. int(), float() and str() request conversions. For example, int("25") produces the integer 25; int("abc") raises ValueError.

5. Inspection and annotations. type(x) reveals the current object type. An annotation such as age: int documents intent and supports external checks, but by itself does not enforce runtime conversion or prevent reassignment.

Python 3 code / example

Code summary: This procedure demonstrates Python's dynamic typing and type casting. It assigns various data types—integer, float, and string—to the same variable to show how the language tracks types at runtime, and concludes by converting a string to an integer to perform a mathematical operation.

Expected output

int float str

30

Explanation of the example

After each assignment, the same name refers to a different object. The type() calls inspect those objects. The final line explicitly converts text to an integer before addition. Dynamic typing is not the same as freely mixing incompatible types; Python still enforces valid operations.

Type information belongs to runtime objects, not permanently to variable names. Distinguish rebinding a name, converting a value and mutating an object.

U.1-T.0.6 | Theory | 20-Mark Preparation

Explain identifiers, keywords, indentation and comments.

Python programs combine programmer-chosen names with reserved language words. Indentation expresses block structure, while comments explain code without being executed. These four concepts are fundamental to reading and writing valid programs.

Key explanation

1. Identifiers. Identifiers name variables, functions, classes and other objects. Examples are total marks and calculate area. They are case-sensitive, cannot begin with a digit and cannot be reserved keywords.

2. Keywords. Keywords have predefined grammatical meaning. Examples include if, else, for, while, def, return, True, False and None. They cannot be used as ordinary variable names. The keyword module can list reserved keywords.

3. Indentation. Leading whitespace groups statements into suites after headers such as if condition:. Statements at the same indentation belong to the same block. Four spaces per level is the usual convention; consistent grouping is the language requirement.

4. Indentation errors. Missing required indentation can raise IndentationError. Inconsistent mixing of tabs and spaces can raise TabError. A correctly indented but misplaced statement may still create a logical error by running inside the wrong block.

5. Comments. A # starts a comment outside a string and continues to the end of the line. Use comments to explain purpose or a non-obvious decision. Several # lines can form a multi-line explanation.

6. Docstrings are different. A string literal at the beginning of a module, function or class can be a documentation string. Triple-quoted strings are strings, not a dedicated multi-line comment syntax; a docstring may be available through __doc _.

Python 3 code / example

Code summary: This procedure determines a student's pass-fail status by comparing their marks against a passing threshold of 40. Using a conditional block, it assigns a pass result and prints it if the score meets the requirement; otherwise, it prints a failure message. The process concludes by printing a completion notification regardless of the outcome.

Expected output

Pass

Check complete

Explanation of the example

marks and result are identifiers. if and else are keywords. The indentation makes two statements part of the successful branch. The final print is outside both branches and runs afterward. The comments explain the program but do not affect its output.

Identifiers provide names, keywords provide grammar, indentation provides structure and comments provide explanation. Use all four correctly to make code valid and readable.

U.1-T.0.7 | Theory | 20-Mark Preparation

Explain int, float, str and bool with examples.

Python provides built-in types for common values. A type determines how a value is represented conceptually and which operations are allowed. int, float, str and bool are immutable: an operation does not modify the existing value in place.

Key explanation

1. int: whole numbers. int represents positive and negative integers and zero, such as 42, -7 and 0. Integers have arbitrary precision subject to available memory. Arithmetic includes +, -, *, //, % and **.

2. float: approximate real numbers. float represents values such as 3.14 and -0.5, generally using binary floating-point. Many decimal fractions are not represented exactly; 0.1 + 0.2 need not equal 0.3 exactly. / returns a float for ordinary integer operands.

3. str: text. str is an immutable sequence of Unicode characters, written using quotes: "Python" or 'Python'. Strings support indexing, slicing, concatenation and methods. The value "25" is text rather than the integer 25.

4. bool: truth values. bool has the values True and False, with this capitalization. Comparisons such as marks >= 40 produce booleans. They control decisions and combine through logical operations. bool is a subclass of int, although its main role is expressing truth.

5. Conversion and checking. Use int ("12"), float ("2.5"), str (12) and bool (0) for suitable conversions. Invalid conversions can fail. type (value) returns a type object; isinstance (value, type name) can test membership in a type hierarchy.

Python 3 code / example

Code summary: This procedure demonstrates basic variable assignment and type identification by defining an item's stock count, price, name, and availability status. It then prints each value alongside its corresponding data type name to illustrate how different pieces of information are represented in memory.

Expected output

Code summary: This block defines a set of variables to demonstrate different data types, associating specific values with an integer, a float, a string, and a boolean.

Explanation of the example

count is a whole number, price includes a fraction, name is quoted text, and available is the result of a comparison. Input read with input() initially has type str; convert it before numerical calculations. bool("False") is True because any nonempty string is truthy.

Choose a type based on meaning: counts use int, approximate measurements use float, text uses str and conditions use bool.

U.1-T.0.8 | Theory | 20-Mark Preparation

Explain the use of type() with an example.

The built-in type() function, in its one-argument form, returns the type object of the supplied object. Its syntax is type(object). It helps examine runtime data, understand expression results and debug unexpected values.

Key explanation

1. Return value. type (10) returns the int class, displayed as <class'int'. It does not return the text"int". Use type (10).__name _ if a readable type name string is wanted.

2. Different built-in objects. Examples include type (2.5) as float, type ("hello") as str, type (True) as bool and type ([1, 2]) as list. Types determine supported operations and methods.

3. Rebinding and dynamic typing. A name can refer to different types at different times. After x = 10, type(x) is int; after x = "ten", it is str. The function reports the current object, not a historical declaration.

4. Diagnosing input errors. If a program concatenates digits instead of adding them, type() may reveal string input. int() or float() performs conversion; type() only inspects and does not change the object.

5. Exact checks and inheritance. type(x) is int checks for the exact class. isinstance(x, int) also accepts subclasses, so isinstance(True, int) is True while type(True) is int is False. isinstance is often more appropriate when inheritance matters.

Python 3 code / example

Code summary: This script demonstrates Python's dynamic typing and type conversion. It highlights how a variable's type can change from an integer to a string and then explicitly converts that string back into an integer to perform a mathematical addition, ultimately verifying the resulting data type.

Expected output

Code summary: This code block demonstrates basic Python type checks and value assignments, outputting the class types for an integer and a string, the string type itself, an integer value of 15, and a boolean True.

Explanation of the example

The first two lines of output show different type objects after reassignment. int(x) creates an integer value suitable for arithmetic; type(x) alone would not do that. The final expression compares the type object with the built-in int class. The less common three-argument form of type() creates classes and is separate from this inspection use.

type() answers what type an object currently has. Keep type inspection, type checking and value conversion distinct in an exam answer.

U.1-T.0.9 | Theory | 20-Mark Preparation

Explain any five built-in string methods with examples.

A string method is an operation accessed through a string object using dot notation, such as text.upper(). Strings are immutable, so transformation methods return new strings rather than changing the original. The returned result must be assigned if it is needed later.

Key explanation

1. upper(). Returns a copy with cased characters converted to uppercase. For example, "Python".upper() gives "Python". Digits and punctuation are unaffected.

2. lower(). Returns a copy with cased characters converted to lowercase. For example, "Python".lower() gives "python". It is useful for simple case-insensitive checks.

3. strip(). Removes leading and trailing whitespace by default. "hello ".strip() gives "hello". It leaves spaces inside the string unchanged.

4. replace(old, new, count). Returns a string with occurrences of old replaced by new. "banana".replace("a", "o", 2) gives "bonona". If count is omitted, all occurrences are replaced.

5. split(sep=None, maxsplit=-1). Splits text into a list of substrings. "red,blue,green".split(",") gives three items. With no separator, runs of whitespace are treated as separators and leading/trailing whitespace does not create empty fields.

Python 3 code / example

Code summary: This snippet demonstrates basic Python string manipulation by applying various built-in methods to transform text, including changing case, removing whitespace, replacing specific characters, and splitting a comma-separated string into a list.

Expected output

: Code summary: This sequence of Python expressions demonstrates basic string literals, mixed-case text variations, a mistaken word, and the creation of a list containing three color strings.

Explanation of the example

upper(), lower(), strip() and replace() return strings; split() returns a list. The last output proves that text still includes its original spaces and capitalization. Method names include parentheses because they are calls. Writing text.upper without parentheses refers to the method instead of calling it.

String methods simplify normalization, cleaning, replacement and tokenization. State the purpose, syntax, return type and example of each requested method.

U.1-T.1.0 | Theory | 20-Mark Preparation

Explain string slicing syntax with examples.

String slicing selects characters from a string to form another string. The general syntax is text[start:stop:step]. The start index is included and the stop index is excluded. Slicing does not alter the original string.

Key explanation

1. Positive indexing and bounds. Indexes begin at zero. For s ="Python", positions 0 through 5 contain P, Y, T, H, O and N. s [1:4] selects positions 1, 2 and 3 and returns"Y.T.H".

2. Omitted bounds. With a positive step, omitted start defaults to the beginning and omitted stop to the end. s [:3] gives"P.Y.T", s [3:] gives"H.O.N" and s gives the full string.

3. Negative indexes. Negative positions count from the right: -1 is the last character. s [-3:] gives"H.O.N" and s [-1] omits the final character. Negative indexes do not by themselves reverse the direction.

4. Step and direction. The step defaults to 1. s [:2] selects alternate characters and gives"P.T.O". A negative step moves backward; s [::-1] reverses the string. Default bounds depend on the step direction.

5. Boundary behavior. Out-of-range slice bounds are clipped, so s [:100] is valid. A direction inconsistent with the bounds can give an empty string, as in s [4:1]. A zero step raises ValueError. In contrast, an out-of-range single index raises IndexError.

Python 3 code / example

Code summary: This script demonstrates various string slicing techniques in Python using the word PYTHON. It showcases how to extract specific substrings through positive and negative indexing, isolate the beginning or end of a sequence, apply step intervals to skip characters, and reverse the string using negative stepping.

Expected output

: Code summary: This sequence represents a pattern of string manipulations, likely for a puzzle or a basic transformation exercise, where a set of letters is rearranged and reversed to form different permutations.

Explanation of the example

For s [4:1:-1], the visited indexes are 4, 3 and 2; position 1 is excluded. This produces O.H.T. The final slice has a positive default step but starts to the right of its stop, so no characters are selected. A slice of length k generally takes O (k) time to construct.

Remember the three rules: start is inclusive, stop is exclusive, and step controls both spacing and direction.

U.1-T.1.1 | Theory | 20-Mark Preparation

Differentiate between find() and index() for strings.

Both find() and index() search for the first occurrence of a substring. Their key difference is the behavior when the substring is absent. Their optional start and end arguments restrict the search to a region.

Key explanation

1. Syntax. Use text.find(sub, start, end) or text.index(sub, start, end). Only sub is required. The region includes start and excludes end, similar to slicing.

2. Successful search. Both return the zero-based index of the first matching occurrence. "banana".find("na") and "banana".index("na") both return 2. The result is a position in the original string, even when start is supplied.

3. Unsuccessful search. find() returns -1 when no match exists. index() raises ValueError, which interrupts normal execution unless handled. Choose the method based on whether absence is expected.

4. Safe condition checking. Use position != -1 to test a find() result. Do not write if text.find(sub), because a match at index 0 is falsey while -1 is truthy. Use sub in text when only a yes/no result is needed.

5. Case and direction. Both methods are case-sensitive and search from left to right. rfind() and rindex() search for the rightmost occurrence. Searching for an empty substring is allowed and follows the selected bounds.

Python 3 code / example

Code summary: This snippet demonstrates the difference between the find and index methods for locating a substring within a string. It shows that find returns the lowest index of the substring or negative one if not found, while index performs the same search but raises a ValueError when the substring is missing, requiring an exception handler to prevent a crash.

Expected output

Code summary: This procedure searches for a substring within a string, returning the starting index of the first occurrence or a failure message if the substring is not found.

Explanation of the example

The first match starts at position 2. Starting the search at position 3 finds the next occurrence at position 4. The missing substring produces a sentinel value with find(), but an exception with index(). The exception handler makes the demonstration complete and allows a clear message.

Use find() when a missing substring is a normal possibility, and index() when failure should be reported through an exception. For pure membership, use in.

U.1-T.1.2 | Theory | 20-Mark Preparation

Explain strip(), Istrip() and rstrip() with examples.

These string methods remove selected characters from the ends of a string. Their syntax is text.strip(chars), text.lstrip(chars) and text.rstrip(chars), where chars is optional. They return new strings because strings are immutable.

Key explanation

1. strip(). Removes characters from both the left and right ends. With no argument, it removes whitespace such as spaces, tabs and newlines. Internal whitespace remains unchanged.

2. Istrip(). Removes only leading characters from the left side. It stops at the first character not in the removal set. Trailing whitespace is preserved.

3. rstrip(). Removes only trailing characters from the right side. Leading whitespace is preserved. It is useful when cleaning line endings while retaining left indentation, if the removal characters are chosen appropriately.

4. Meaning of chars. The argument is a set of individual characters, not an exact prefix or suffix. "xyHelloyx".strip("xy") removes any x or y from either end and returns "Hello".

5. Common mistakes. strip() does not remove every space everywhere and does not modify the original string. Do not use strip(".txt") to reliably remove a literal extension; its argument means any of those characters. Exact affix removal is a different operation.

Python 3 code / example

Code summary: This code demonstrates the functionality of Python's string trimming methods by applying strip, lstrip, and rstrip to remove whitespace or specific characters from the beginning and end of strings, using repr to explicitly show the resulting string boundaries.

Expected output

Code summary: This sequence of strings primarily consists of the word Python repeated multiple times, interspersed with hello world and Hello.

Explanation of the example

repr() displays quotes so retained spaces are visible. The first three results distinguish both ends, left only and right only. The internal space in hello world remains.

The final result shows that s was not changed. Assign s = s.strip() when the cleaned result should replace the current binding.

Choose the method according to which end needs cleaning, and remember that chars describes removable characters rather than a complete word.

U.1-T.1.3 | Theory | 20-Mark Preparation

Explain string formatting using format().

The str.format() method creates formatted text by replacing fields in a template with supplied values. General syntax is "template {field:specification}".format(arguments). It returns a new string and does not modify the template.

Key explanation

1. Automatic positional fields. Empty fields {} use arguments in order: "{} scored {}".format("Anu", 90) produces "Anu scored 90". Supply enough arguments for the fields.

2. Numbered positional fields. Indexes select arguments explicitly. {"1}, {0}.format("first", "second") produces "second, first". A numbered field may be reused.

3. Named fields. Names improve readability: {"name}{mark}.format(name="Anu", mark=90). Missing named arguments raise KeyError. Do not mix automatic and manual positional numbering.

4. Precision and numeric formatting. A colon introduces a format specification. {:.2f} displays a fixed-point number with two digits after the decimal point. {:,} adds grouping separators to a number. Formatting changes the displayed text, not the stored numeric value.

5. Width, alignment and braces. {: greater than 8} right-aligns in a minimum width of 8; {: less than 8} left-aligns; {: ^8} centers. Width does not truncate a longer value. Write {{ and}} to include literal braces.

Python 3 code / example

Code summary: This code demonstrates various string formatting techniques using the format method to handle dynamic data insertion. It showcases positional indexing, named arguments for clarity, precision control for floating-point numbers, thousands separators for large integers, right-alignment for visual padding, and the escaping of curly braces to include literal brackets in the output.

Expected output

Code summary: This code snippet demonstrates basic variable assignment and rudimentary arithmetic operations in Python, calculating a total value by multiplying a price of 12.50 by a quantity of 1,000 to result in 12,500.

Explanation of the example

The examples demonstrate argument selection separately from presentation. The numeric value 12.5 is shown as 12.50 to suit a report. Vertical bars make the alignment spaces visible. An incompatible specification, such as a floating-point code applied to unsuitable text, can raise an error.

format() separates the message template from the values and gives precise control over numbers and alignment, making it useful for reports and tables.

U.1-T.1.4 | Theory | 20-Mark Preparation

Differentiate mutable and immutable sequences using lists and tuples.

A sequence is an ordered collection supporting positional access. Mutability describes whether the same object can be changed after creation. A list is mutable; a tuple is immutable. Both can contain duplicate values and objects of different types.

Key explanation

1. Creation and access. Lists commonly use square brackets, for example [10, 20]. Tuples commonly use parentheses with commas, for example (10, 20). Both support indexing, negative indexing, slicing, iteration and len.

2. Element assignment. A list permits a [0] = 99. The equivalent assignment to a tuple raises TypeError. A tuple has fixed element references, while a list allows replacements.

3. Changing size. A list can grow or shrink through append(), extend(), insert(), pop() and remove(). Tuples have no such mutating methods. Concatenating tuples produces a tuple value; it does not mutate the original.

4. Aliasing and rebinding. Two names may refer to the same list, so mutation through one is visible through the other. Reassigning a name to another tuple is permitted; immutability does not prevent variable rebinding.

5. Nested values and hashing. A tuple can contain a mutable object such as a list, and that inner list can change. A tuple is hasable only when all its elements are hasable. Lists are unhashable and cannot be dictionary keys.

6. Typical use. Use lists for changing collections such as shopping items. Use tuples for fixed records such as coordinates. Select according to whether the collection should change, not merely because both store several values.

Python 3 code / example

: Code summary: This sequence demonstrates the fundamental differences between mutable and immutable data structures in Python. It first shows that assigning one list to another creates a reference, meaning changes to the original list are reflected in the reference. It then contrasts this with tuples, which are immutable and require the creation of a new tuple object to add elements. Finally, it illustrates a hybrid case where a mutable list nested inside an immutable tuple can still be modified in place.

Expected output

[99, 20, 30]

(10, 20, 30)

([1,2,4],3)

Explanation of the example

b observes mutations because it aliases a. The assignment to t binds it to a concatenated tuple. In u, the tuple still refers to the same list and integer, but the contained list changes. This illustrates why tuple immutability is not a guarantee that every nested object is immutable.

Mutation changes an object; rebinding changes what a name refers to. This distinction explains the central difference between lists and tuples.

U.1-T.1.5 | Theory | 20-Mark Preparation

Explain lists and any five built-in list methods.

A list is an ordered, mutable sequence written using square brackets. It allows duplicates and heterogeneous elements, such as [10, "Python", True]. Positions begin at zero, and negative indexes count from the end.

Key explanation

1. append (x). Adds one object at the end. a.append (40) increases the list length by one. If x is another list, that entire list is appended as a single nested element.

2. extend (iterate). Adds each item from an iterate to the end. a.extend ([50, 60]) adds two elements. A string is itable, so extending with"ab" adds two characters.

3. insert (1, 10). Inserts x before position i and shifts later elements right. a.insert (1, 15) places 15 at index 1. Inserting within a long list generally requires movement of elements.

4. remove (x). Deletes the first item equal to x. a.remove (20) removes the first 20, not the element at index 20. It raisesChinese textError if the value is absent.

5. pop(i=-1). Removes and returns the element at an index. With no argument it removes the last item. It raises IndexError for an empty list or an invalid index.

6. Mutation and return values. append(), extend(), insert() and remove() modify the existing list and return None. pop() returns the removed value. Avoid assigning a = a.append(x), which binds a to None.

Python 3 code / example

Code summary: This procedure demonstrates basic list manipulation in Python. It begins by initializing a list and uses a sequence of operations to modify the collection: appending and extending to add single or multiple elements, inserting a value at a specific index for precise positioning, and removing a specific value to filter the list. It concludes by popping the final element to retrieve it and output the final state of the list.

Expected output

[10, 20, 30, 40] [10, 15, 30, 40, 50, 60] Removed: 60 [10, 15, 30, 40, 50]

Explanation of the example

The first list grows by one value. extend adds two more; insert places 15 between 10 and 20; remove deletes 20 by value. Finally pop returns 60 and shortens the list. Indexing and slicing can be used to inspect the results without invoking a method.

Lists suit collections that change. Explain whether each method acts by value or by index and whether it returns a useful value or None.

U.1-T.1.6 | Theory | 20-Mark Preparation

Explain tuples, their properties and built-in methods.

A tuple is an ordered, immutable sequence of objects. A tuple commonly appears as comma-separated values inside parentheses, such as (10, 20, 10). The comma forms a tuple; parentheses mainly group the expression.

Key explanation

1. Creation. An empty tuple is. A singleton is (5,), with a required comma; (5) is only the integer 5 in parentheses. tuple (Able) constructs a tuple from an锤

2. Sequence properties. Tuples preserve order, allow duplicates and may mix types. Indexing, negative indexing, slicing, iteration, membership and len() work much as they do for lists.

3. Immutability. A tuple does not support replacing, adding or deleting its element references in place. t [0] = 9 raises TypeError. Concatenation and repetition create tuple results rather than mutating the original.

4. count (value). Returns the number of occurrences of a value. (10, 20, 10). count (10) gives 2. A missing value has count zero.

5. index (value, start, stop). Returns the position of the first matching value within optional bounds. (10, 20, 10). index (20) gives 1. A missing value raisesChinese textError.

6. Use and limitations. Tuples support unpacking such as x, y = (3, 4). They suit fixed records. A tuple may contain a mutable list, and it is usable as a dictionary key only when every element is hashable. len, min and max are functions, not tuple methods.

Python 3 code / example

Code summary: This snippet demonstrates basic Python tuple operations, showing how to access elements by index, extract slices, and use built-in methods like count and index to analyze tuple contents. It further illustrates the definition of a single-element tuple and the use of sequence unpacking to assign tuple values to individual variables.

Expected output

: Code summary: This input block provides a sequence of configuration parameters and constraints, likely defining a problem instance. It specifies a grid or boundary of 10 by 30, a coordinate pair of 20 and 10, a set of three individual integer constraints or flags, and a final target or value of 7.

Explanation of the example

The tuple maintains the two occurrences of 10 and their positions. count() and index() are its two main public sequence methods. Unpacking assigns the two coordinate values to separate names; normally the number of targets must match the number of items unless a starred target is used.

A tuple is best understood as a fixed ordered sequence. Remember the singleton comma, the two methods and the distinction between outer immutability and mutable contents.

U.1-T.1.7 | Theory | 20-Mark Preparation

Explain sets and their properties with an example.

A set is a mutable collection of distinct hashable elements. It models the mathematical idea of membership and supports operations such as union and intersection. A set is unordered: it provides no positional indexing or guaranteed display order.

Key explanation

1. Creation and uniqueness. Use {1, 2, 3} or set(itable). Repeated equal elements are represented once. Create an empty set with set(); {} creates an empty dictionary.

2. Element restrictions. Elements must be hashable, so integers, strings and tuples of hashable elements can be included. Lists, dictionaries and mutable sets cannot be set elements. Frozenset is an immutable set type.

3. Adding and removing. add(x) inserts an element, while update(itable) inserts multiple elements. remove(x) deletes an existing element and raises KeyError if absent. discard(x) does not raise an error when x is absent.

4. Set operations. A | B is union, A & B is intersection, A - B is difference and A B is symmetric difference. A <= B tests whether A is a subset of B.

5. Access and performance. Use in for membership and a loop for traversal. Indexing and slicing are unsupported. Membership is O (1) on average under ordinary hash-table assumptions, making sets useful for duplicate removal and membership tests.

Python 3 code / example

: Code summary: This snippet demonstrates basic set operations in Python. It initializes two sets and showcases how to perform union, intersection, difference, and symmetric difference, sorting the results of each to ensure a consistent output order. It also illustrates set mutation by adding an element and attempting to remove a non-existent one, concluding with a membership check to verify the set's final state.

Expected output

True

Explanation of the example

sorted is used only to display deterministic results and returns a list; it does not make the set ordered. The duplicate 2 is eliminated. Union combines both sets, intersection keeps the common 3, and symmetric difference excludes common elements. discard (9) safely leaves a unchanged.

Use sets when uniqueness and membership matter. Choose a list or tuple when position, duplicates or sequence order must be retained.

U.1-T.1.8 | Theory | 20-Mark Preparation

Explain dictionaries and keys(), values() and items().

A dictionary is a mutable mapping from unique hashable keys to values. Write entries as key: value pairs inside braces. Unlike a list, it normally retrieves a value by a meaningful key rather than a position.

Key explanation

1. Keys and values. Keys must be hashable, for example strings, integers or tuples of hashable values. values can be arbitrary objects and may repeat. Assigning an existing key replaces its value rather than adding a duplicate key.

2. Access and mutation. d[key] retrieves a value and raises KeyError if the key is missing. d.get(key, default) returns a fallback for a missing key. Assignment inserts or updates, and del d[key] removes an entry.

3. keys(). Returns a dynamic view of the keys. It can be iterated or converted with list(d.keys(). The expression key in d tests keys directly; it does not search values.

4. values(). Returns a dynamic view of values in corresponding iteration order. Duplicate values remain. list(d.values()) provides a list snapshot at that moment.

5. items(). Returns a dynamic view of (key, value) pairs. It is useful for loops such as for key, value in d.items(): The pair can be unpacked into two names.

6. Order and views. Python 3.7 and later guarantee insertion order. A saved view reflects subsequent dictionary changes, while a list snapshot does not. Avoid adding or removing entries while iterating over that dictionary.

Python 3 code / example

: Code summary: This snippet demonstrates basic dictionary operations in Python, illustrating how to store student data and retrieve specific values, keys, and item pairs. It highlights the dynamic nature of dictionary views, showing that updating the dictionary reflects in existing key views, and demonstrates the use of the get method to safely handle missing keys with a default value.

Expected output

Code summary: This code snippet demonstrates basic Python list and tuple operations, showcasing how to group labels and values into pairs and manage simple data structures containing strings and integers.

Explanation of the example

The original keys and values appear in matching insertion order. items() packages each association as a pair. The saved keys view includes grade after insertion because it is live. Direct dictionary membership checks keys, so "Anu" in student is False unless "Anu" is itself a key.

Dictionaries efficiently represent labeled information. Distinguish keys, values and pairs, and distinguish live views from list snapshots.

U.1-T.1.9 | Theory | 20-Mark Preparation

Explain negative indexing in lists.

Negative indexing accesses sequence elements relative to the end. For a nonempty list, -1 selects the last element, -2 the second-last and so on. It is useful when the required position is known from the end rather than the beginning.

Key explanation

1. Index mapping. For a list of length n, a valid negative index i refers to positive position n + i. If n is 5, index -1 maps to 4 and index -5 maps to 0.

2. Valid range. Single-element indexes lie between -n and n-1 inclusive. A value outside that range raises IndexError. Empty lists have no valid single-element index. -0 is the same as 0, not a special last position.

3. Reading and updating. a [-1] reads the last value. Because lists are mutable, a [-1] = 99 replaces the last element. Negative indexing changes how a position is specified, not the list order.

4. Negative indexes in slicing. a [-3:] selects the final three items. a [-1] selects everything except the final item. Slice stop positions remain excluded, and slice bounds can be clipped rather than raising IndexError.

5. Index sign versus step. A negative index is not a reverse operation. Reversal is expressed by a negative slice step, such as a [::-1]. a [-3:] still lists the selected elements in their original left-to-right order.

Python 3 code / example

Code summary: This script demonstrates Python list indexing and slicing techniques. It accesses specific elements from the end of the list using negative indices and extracts a sub-list from the third-to-last element onward. Finally, it attempts to modify a value based on its position and reverses the entire list using a stride of negative one.

Expected output

Code summary: This code block provides a series of test cases consisting of individual integers and lists of integers, likely used to verify the correctness of a sorting or searching algorithm across various scenarios, including unsorted and pre-sorted data.

Explanation of the example

The last element starts at positive index 4 and negative index -1. Updating through -1 changes that same element. The final expression creates a reversed list through slicing; it does not reverse a in place. Accessing a [-6] here would raise IndexError.

Count backward starting at -1 and translate using n + i when uncertain. Negative indexing provides convenient end-relative access.

U.1-T.2.0 | Theory | 20-Mark Preparation

Differentiate between append() and extend() for lists.

append() and extend() both mutate a list by adding data at the end. The difference is whether the argument is inserted as one object or iterated to insert its individual elements.

Key explanation

1. append(x). Appends x as exactly one element. The length increases by one regardless of whether x is a number, string, list or another object. Appending a list creates a nested list element.

2. extend(iterate). Iterates over its argument and appends each produced item. The length increases by the number of yielded items. A list, tuple, string, range or other iterable can be supplied.

3. Argument restrictions. append (5) is valid. extend (5) raises TypeError because an integer is notChinese text. extend ([5]) is valid and adds the single number.

4. Return values and identity. Both modify the same list and return None. Aliases to the list see the change. Do not write a = a.extend(b), which discards the list binding in favor of None.

5. Nesting and cost. extend removes one level of iterable packaging; it does not recursively flatten nested structures. append has amortized O (1) cost, while extending by k elements takes O (k) time on average.

Python 3 code / example

Code summary: This procedure demonstrates the fundamental difference between the append and extend methods for Python lists. It shows that append adds a single object as a new element at the end of the list, regardless of whether that object is a list or a string, whereas extend iterates over an iterable and adds each of its individual elements to the list. The result is a comparison of how list lengths and contents diverge when adding nested lists versus flat elements, and when adding strings as single units versus sequences of characters.

Expected output

: Code summary: This sequence of operations demonstrates a list flattening process, where nested sub-lists are unpacked into a single-level list. It transforms nested structures into linear sequences of elements, handling both integers and strings to ensure all individual items are accessible at the top level.

Explanation of the example

append ([3, 4]) inserts one list object, so a has three items. extend ([3, 4]) inserts two integers, so b has four.

Appending a string keeps it whole, whereas extending with a string adds its characters. Extending with [[3, 4]] would still insert one nested list.

Use append() to add one item and extend() to add the items supplied by an iterable. The distinction concerns the resulting structure, not just syntax.

U.1-P.0.1 | Programming | 20-Mark Preparation

Swap two variables without a temporary variable.

Swapping exchanges the values referenced by two variables. Python supports parallel assignment: the right-hand expressions are evaluated before either target is rebound. This avoids an explicitly named third variable and works for many object types.

Algorithm

1. Input. Read two integers a and b. The same swap statement also works for strings and other objects.

2. Process. Execute a, b = b, a. The old value of b becomes the new a, and the old value of a becomes the new b.

3. Output. Print the values before and after swapping to demonstrate the exchange.

Python 3 code / example

Code summary: This procedure captures two integer inputs from the user and swaps their values using tuple unpacking to reverse their original positions before printing the result.

Sample input (in prompt order): 10 | 25

Expected output

: Code summary: This procedure swaps the positions of two values, transitioning from an initial state of 10 and 25 to a final state of 25 and 10.

Dry run and correctness

Initially a = 10 and b = 25. Python evaluates the pair of right-hand values as 25 and 10, then binds the targets in order. Therefore a becomes 25 and b becomes 10. Writing a = b followed by b = a would lose the original a and make both variables 25. Parallel assignment avoids this logical error.

Edge cases and exam notes

Equal values remain equal after swapping; zero and negative integers also work. Input must be valid integer text. Arithmetic swapping using addition and subtraction is possible, but parallel assignment is clearer and does not require numeric operands.

O (1) time and O (1) extra references for the swap. Input conversion costs depend on the length of the entered numbers.

U.1-P.0.2 | Programming | 20-Mark Preparation

Check whether a string is a palindrome.

A palindrome reads the same forward and backward, such as madam or level. This answer uses an exact, case-sensitive comparison: spaces and punctuation count as characters. Stating this assumption makes the result unambiguous.

Algorithm

1. Input. Read a string without stripping it, because leading and trailing spaces are part of the exact comparison.

2. Reverse. Use text [::-1] to construct the reverse. The negative step visits the string from end to beginning.

3. Compare and report. If the original equals its reverse, print Palindrome; otherwise print Not a palindrome.

Python 3 code / example

Code summary: This procedure determines if a user-provided string is a palindrome by reversing the input text and comparing it to the original. If the two strings are identical, the program identifies the text as a palindrome; otherwise, it identifies it as not a palindrome.

Sample input (in prompt order): madam

Expected output

Palindrome

Dry run and correctness

For madam, the reversed characters are m, a, d, a, m, giving the same string. For python, the reverse is nohtyp, so the equality test is false. The slice does not alter the original string; it creates the value used for comparison.

Edge cases and exam notes

An empty string and any single-character string are palindromes under this definition. Madam is not an exact palindrome because M and m differ. If the question instead specifies ignoring punctuation and case, normalize first with "" join(ch.lower() for ch in text if ch.isalnum()) and apply the same comparison.

O(n) time and O(n) extra space for a string of n characters, because the reversed copy contains n characters.

U.1-P.0.3 | Programming | 20-Mark Preparation

Count vowels and consonants in a string.

A vowel is one of a, e, i, o and u. For this program, consonants are the remaining English letters a-z. Uppercase and lowercase are treated equally; spaces, digits, punctuation and other characters are ignored.

Algorithm

1. Initialize. Read text and set vowels and consonants to zero.

2. Scan. Convert to lowercase and examine each character once. Increment vowels when the character is in "aeiou".

3. Classify remaining letters. Otherwise increment consonants only when the character is between "a" and "z".

4. Display. Print both counts after the loop.

Python 3 code / example

Code summary: This procedure calculates the total count of vowels and consonants in a user-provided string. It normalizes the text to lowercase to ensure case-insensitive matching, then iterates through each character to categorize it as either a vowel or a consonant, provided the character is an alphabetic letter. The final result is a printout of the cumulative counts for both categories.

Sample input (in prompt order): Hello World!

Expected output

Code summary: This procedure analyzes a given string to count and display the total number of vowels and consonants present.

Dry run and correctness

In hello world, e, o and o contribute three vowels. The letters h, l, l, w, r, l and d contribute seven consonants. The space and exclamation mark satisfy neither condition. The if-elif structure ensures a vowel cannot also be counted as a consonant.

Edge cases and exam notes

Empty text produces zero for both counts. Digits do not count as consonants. The letter y is counted as a consonant. The explicit a-z condition avoids accidentally classifying every non-English alphabetic character as an English consonant.

O (n) time for n characters. The lowercase copy requires O (n) extra space; the two counters require O (1) auxiliary storage.

U.1-P.0.4 | Programming | 20-Mark Preparation

Find string length without using len().

The length of a string is the number of characters visited during iteration. A counter can measure it without calling len(). In Python, string iteration counts Unicode code points; a visually combined symbol can sometimes contain more than one code point.

Algorithm

1. Input and initialization. Read the string and set count = 0.

2. Iteration. For every character encountered, add one to count. The character value itself does not need to be inspected.

3. Output. After all characters have been visited, display count as the length.

Python 3 code / example

Code summary: This procedure calculates the length of a user-provided string by iterating through every character and incrementing a counter, ultimately printing the total character count.

Sample input (in prompt order): Python 3

Expected output

Length: 8

Dry run and correctness

The loop visits P, y, t, h, o, n, a space and 3. The counter therefore takes values 1 through 8. The loop invariant is: after processing k characters, count equals k. Initially k = 0 and count = 0; each iteration preserves the invariant by increasing both by one. At termination, count equals the total number of characters.

Edge cases and exam notes

An empty string produces zero because the loop never runs. Spaces, digits and punctuation count as characters. input() removes the terminating newline entered to submit the text, so that newline is not counted. Do not use strip() here because it would change the string being measured.

O (n) time and O (1) auxiliary space, excluding the input string. In ordinary code, len (text) is clearer and obtains a stored string length in O (1) time.

U.1-P.0.5 | Programming | 20-Mark Preparation

Convert a string to uppercase and lowercase.

Python strings provide upper() and lower() methods for case conversion. Each returns a transformed string because strings are immutable. Characters without case, such as digits and most punctuation, are retained.

Algorithm

1. Input. Read the string exactly as entered.

2. Convert. Call text.upper() and text.lower(), storing the returned strings separately.

3. Output. Print the uppercase and lowercase versions with descriptive labels.

Python 3 code / example

Code summary: This procedure captures a user-provided string and transforms it into both uppercase and lowercase versions to demonstrate basic string manipulation, outputting both modified versions to the console.

Expected output

Code summary: This snippet demonstrates basic string case transformation by displaying a string in both uppercase and lowercase formats.

Dry run and correctness

In the uppercase result, each cased English letter becomes its capital form. In the lowercase result, H and P become h and p and already lowercase letters remain lowercase. Spaces, the digit 3 and the exclamation mark are unchanged. The variable text continues to refer to the original mixed-case string.

Edge cases and exam notes

An empty string returns an empty string for both operations. Text already in the requested case stays equivalent. Python applies Unicode case rules, and some Unicode conversions can change string length. For caseless comparison across languages, casefold() is often more suitable, but upper() and lower() directly answer this question.

O(n) time and O(n) space for ordinary case conversion of n input characters, with storage for the converted results.

U.1-P.0.6 | Programming | 20-Mark Preparation

Remove duplicate elements from a list.

The aim is to retain one copy of each distinct value. This solution preserves the order of first occurrence and builds a new list, leaving the input list unchanged. It uses equality-based membership checks and does not require a set.

Algorithm

1. Input. Read space-separated integers into a list and initialize an empty result list.

2. Scan. For each input item, check whether it is already present in the result.

3. Retain first occurrences. Append the item only if it has not appeared before.

4. Output. Display the resulting list of distinct values.

Python 3 code / example

Code summary: This procedure removes duplicate values from a user-provided list of integers while preserving their original order. It first converts a space-separated input string into a list of integers, then iterates through that list to collect only the first occurrence of each single value into a new list, ultimately outputting the sequence of unique integers.

Code summary: This procedure processes a sample input sequence of six integers—4, 2, 4, 3, 2, 1—to demonstrate the expected input order for the algorithm.

Expected output

Without duplicates: [4, 2, 3, 1]

Dry run and correctness

The successive retained results are [4], [4, 2], unchanged for the second 4, [4, 2, 3], unchanged for the second 2, and finally [4, 2, 3, 1]. After each iteration, unique contains exactly the distinct values seen so far in their first-occurrence order.

Edge cases and exam notes

Empty input yields an empty list; all-equal input yields one value. A set-based conversion can lose the intended sequence order. For hashable values, list(dict.fromkeys(numbers)) is a concise order-preserving alternative with average linear time. The explicit loop is straightforward to explain in an exam.

O(n squared) time in the worst case because each list membership check can scan earlier retained values; O(n) extra space. A seen set plus a result list can reduce expected time to O(n) for hashable elements.

U.1-P.0.7 | Programming | 20-Mark Preparation

Find the maximum and minimum elements of a list.

The maximum is the greatest value and the minimum is the least. A single scan can find both without sorting or calling max() and min(). For an empty list, neither extreme exists, so the program reports that case separately.

Algorithm

1. Input and guard. Read integers. If the list is empty, display an explanatory message.

2. Initialize. For a nonempty list, initialize both smallest and largest to the first element.

3. Compare. Visit each element. Update largest when a larger value is found and smallest when a smaller value is found.

4. Output. Print the final maximum and minimum.

Python 3 code / example

Code summary: This procedure identifies the minimum and maximum values from a user-provided list of integers. After converting the input string into a list of integers, it handles empty input as a special case. If integers are present, it iterates through the list once to track and update the smallest and largest values encountered, ultimately printing both extremes.

Expected output

Code summary: This block defines a set of numeric constraints, establishing a maximum threshold of 15 and a minimum threshold of -3.

Dry run and correctness

Both candidates begin at 8. Reading -3 updates the minimum to -3. Reading 15 updates the maximum to 15. Neither 0 nor 6 changes either candidate. At every stage, the candidates are the extrema of the processed prefix, so they are the extrema of the whole list when the loop ends.

Edge cases and exam notes

A single-element list has the same minimum and maximum. All-negative data works because initialization uses an actual list value instead of zero. Duplicate values do not change the result. Built-ins max(numbers) and min(numbers) are valid shorter alternatives when a manual algorithm is not requested.

O (n) time and O (1) auxiliary space beyond the input list. Sorting would do unnecessary work for this task.

U.1-P.0.8 | Programming | 20-Mark Preparation

Merge two dictionaries into one.

Merging creates a mapping containing the entries of both input dictionaries. If both dictionaries contain the same key, a conflict rule is necessary. This solution keeps the value from the second dictionary and preserves both original dictionaries.

Algorithm

1. Create input mappings. Define two dictionaries with some distinct keys and one shared key to demonstrate collision behavior.

2. Copy. Create merged as a shallow copy of the first dictionary.

3. Update. Call merged.update(second) to insert new keys and replace values for existing keys.

4. Display. Print the combined mapping.

Python 3 code / example

Code summary: This procedure merges two dictionaries by creating a copy of the first and updating it with the entries from the second. This ensures that any overlapping keys are resolved by prioritizing the values from the second dictionary, ultimately producing a single combined dictionary.

Sample input (in prompt order): No keyboard input; data is included in the program.

Expected output

Code summary: This operation merges multiple data sources into a single object, resulting in a combined set of key-value pairs where each unique key is mapped to its corresponding value.

Dry run and correctness

Initially merged contains a: 10 and b: 20. Updating with the second mapping replaces the value of b with 99 and inserts c: 30. The original first still contains b: 20 because the top-level dictionary was copied. The order is a, b, c: updating b changes its value without moving its existing position.

Edge cases and exam notes

If a dictionary is empty, the result contains the entries of the other. This is a shallow merge: nested dictionaries are not recursively combined, and nested mutable objects may still be shared. update() returns None, so do not assign merged = merged.update(second). Change the update order if the first dictionary should win conflicts.

Average O(n + m) time and O(n + m) result space for input sizes n and m, under usual dictionary hashing assumptions.

U.1-P.0.9 | Programming | 20-Mark Preparation

Count each character frequency using a dictionary.

A frequency dictionary maps each character to the number of times it appears. This solution treats uppercase and lowercase as different characters and includes spaces and punctuation. The dictionary avoids creating a separate counter for every possible character.

Algorithm

1. Initialize. Read text and create an empty frequency dictionary.

2. Count. For each character ch, obtain its existing count with get(ch, 0) and store that count plus one.

3. Display. Iterate over items() to print each character and count. Use repr() so whitespace characters can be recognized.

Python 3 code / example

Code summary: This procedure calculates the frequency of each character in a user-provided string. It first iterates through the text to populate a dictionary that tracks occurrences of every character, then prints each unique character and its corresponding count.

Expected output

: This code defines a dictionary mapping characters to their respective frequency counts, specifically recording that 'a' appears 3 times, 'n' appears 2 times, and 'b' appears 1 time.

Dry run and correctness

For banana, the updates are b:1, a:1, n:1, a:2, n:2, a:3. get(ch, 0) supplies zero when a character has not yet appeared, avoiding a missing-key error. The final items loop unpacks each key-value pair. In Python 3.7+, characters are displayed in their first-insertion order.

Edge cases and exam notes

An empty string prints no character rows. The string Aa produces separate counts for A and a. A space is shown as '' using repr(). If case-insensitive counting is required, normalize the input before counting. After processing any prefix, the sum of stored frequencies equals the number of processed characters.

Expected O(n) counting time and O(k) dictionary space, where k is the number of distinct characters and k is at most n.

U.1-P.1.0 | Programming | 20-Mark Preparation

Sort numbers in descending order without sort().

Descending order places the greatest element first and the least last. This solution uses selection sort and avoids both sort() and sorted(), demonstrating the sorting logic directly. The original input list is rearranged in place.

Algorithm

1. Choose a position. For each index i from zero through n-2, assume the largest remaining item is at i.

2. Find the largest remaining value. Scan indexes i+1 through n-1 and remember the index of the greatest value.

3. Swap. Exchange that value with the item at i using parallel assignment.

4. Repeat and output. After each pass, the next greatest value is fixed. Print the list after all passes.

Python 3 code / example

Code summary: This procedure implements a selection sort algorithm to arrange a list of user-provided integers in descending order. It works by iteratively scanning the unsorted portion of the list to identify the index of the largest remaining element and swapping it into the current primary position, effectively building a sorted sequence from the start of the list until all elements are processed.

Expected output

Descending: [5, 4, 2, 1]

Dry run and correctness

Pass 1 finds 5 and swaps it with 4: [5, 1, 4, 2]. Pass 2 finds 4 in the remaining region: [5, 4, 1, 2]. Pass 3 selects 2: [5, 4, 2, 1]. After each pass, the processed prefix contains the largest values in descending order, and no later value exceeds the last fixed choice.

Edge cases and exam notes

Empty and one-element lists need no swaps. Negative numbers and duplicates are handled by the same comparison. This selection sort is not stable in general: equal-valued records could change relative order. The built-in sorted(..., reverse=True) would normally be preferred, but it would hide the requested algorithm.

O (n squared) time in best, average and worst cases; O (1) auxiliary space. There are n (n-1) /2 comparisons and at most n-1 exchanges.

U.2-T.0.1 | Theory | 20-Mark Preparation

Explain the different types of Python operators.

An operator performs an operation on one or more operands. Python provides arithmetic, comparison, assignment, logical, bitwise, membership and identity operators. The operand types determine which operations are meaningful.

Key explanation

1. Arithmetic. +, -, *, /, //, % and ** perform addition, subtraction, multiplication, true division, floor division, remainder and exponentiation. For example, 7 // 2 is 3 and 7 % 2 is 1.

2. Comparison. ==, !=, <, >, <= and >= compare values and normally produce bool results. For example, 5 greater than 3 is True. Comparisons can be chained: 0 less than x less than 10.

3. Assignment. The = statement binds a target; augmented assignments such as +=, -= and * = combine an operation with assignment. For example, x += 2 increases a numeric x by two.

4. Logical. and, or and not combine truth tests. For booleans, True and False is False. and and or short-circuit and can return operands rather than bool values.

5. Bitwise. &, |, ^, ~, << and >> operate on integer bit patterns. For example, 5 & 3 gives 1. Do not confuse bitwise & with logical and.

6. Membership and identity. in and not in test containment, such as "a" in "cat". is and is not compare object identity, such as a is b; they do not substitute for value equality.

Python 3 code / example

Code summary: This sequence demonstrates basic Python operations, including arithmetic calculations, relational and logical comparisons, bitwise masking, membership testing, and object identity verification.

Expected output

: Code summary: This sequence of values and booleans represents a series of raw data inputs and flag checks, though no named algorithm or formal procedure is defined in the provided text.

Explanation of the example

The first line groups several arithmetic results. The assignment changes a to 8. The bitwise result comes from 0101 and 0011 = 0001. x and y refer to the same list, so the identity test is true. Division or remainder by zero raises ZeroDivisionError.

Classify operators by purpose and include an expression with its result for each class. Use parentheses when combining classes makes the intended evaluation unclear.

U.2-T.0.2 | Theory | 20-Mark Preparation

Explain operator precedence with an example.

Operator precedence decides how an expression is grouped when multiple operators occur without parentheses. Associativity determines grouping among operators at the same precedence level. Precedence is a parsing rule, not a claim that all subexpressions execute in an arbitrary order.

Key explanation

1. Common high-to-low order. For common expressions: grouping parentheses; exponentiation **; unary +, - and ~; *, /, // and %; + and -; shifts; bitwise & then ^ then |; comparisons including membership and identity; not; and; or.

2. Arithmetic example. 2 plus 3 times 4 gives 14 because multiplication binds more tightly than addition. open parenthesis 2 plus 3 close parenthesis times 4 gives 20 because parentheses explicitly group the addition.

3. Associativity. Most binary arithmetic operators at the same level group left to right: 20 divided by 5 times 2 gives 8.0. Exponentiation groups right to left: 2 to the power of 3 to the power of 2 means 2 to the power of 3 times 2, giving 512.

4. Unary and exponent caveat. -2 **2 means -(2 **2), giving -4. (-2) **2 gives 4. Exponentiation permits a unary expression on its right, so 2 ** -2 gives 0.25.

5. Logical combinations. Comparisons bind more tightly than not, and not more tightly than and, which binds more tightly than or. Parentheses can make a condition easier to read even when they are not required.

Python 3 code / example

Code summary: This script demonstrates the fundamental rules of operator precedence and associativity in Python. It evaluates various expressions to show how multiplication and exponentiation take priority over addition, how parentheses override default order, how left-to-right evaluation handles division and multiplication, and how right-to-left associativity applies to nested exponents. Finally, it illustrates the precedence of logical operators, where the 'and' operation is evaluated before the 'or' operation.

Expected output

Code summary: This block defines a set of configuration constants, specifying numerical parameters including 14 and 20, a float value of 8.0, a size of 512, a range from -4 to 4, and a boolean flag set to True.

Explanation of the example

For the final condition, False and False is grouped together before or, so the grouped expression is True or (False and False). Short-circuiting means Python can return after the first True without evaluating the right side. Parentheses express grouping; short-circuit rules determine whether an operand must run.

Use precedence to explain evaluation, associativity to resolve equal levels, and parentheses to make intended grouping explicit.

U.2-T.0.3 | Theory | 20-Mark Preparation

Differentiate between = and ==.

The symbols = and == serve different purposes. A single equals sign is used in assignment statements to bind a target to a value. A double equals sign is the equality comparison operator and asks whether two values compare equal.

Key explanation

1. Assignment syntax. target = expression evaluates the right-hand expression and binds or assigns the result to the target. For example, marks = 80 stores a reference to the integer value in the name marks.

2. Comparison syntax. left == right compares values. For example, marks == 80 produces True when marks is 80 and False otherwise. It does not reassign marks.

3. Where used. Assignment appears as a statement such as total = price * quantity. Equality appears inside expressions, conditions and print calls, such as if marks == 80:.

4. Targets and chaining. An assignment target must be assignable; 10 = x is invalid. a = b = 0 assigns the same initial value to both names. a == b == 0 is instead a chained comparison.

5. Common errors. if x = 5: is invalid Python syntax. Write if x == 5:. Python also has a distinct assignment expression operator :=, but it does not change the meaning of = or ==. == compares equality; is compares identity.

Python 3 code / example

Code summary: This sequence demonstrates basic variable assignment and conditional logic by initializing a marks variable, comparing it against specific values to test equality, and using an if statement to execute a print command only when the value equals 80. It concludes by updating the variable through addition to show how a value can be incremented.

Expected output

Code summary: This block consists of a sequence of literal values, including integers, booleans, and a string, without a defined algorithmic structure or named procedure.

Explanation of the example

The first assignment establishes marks as 80. The comparisons produce truth values while leaving it unchanged. The final assignment evaluates the old marks plus five, then binds marks to 85. Different objects can compare equal, and user-defined classes may customize equality behavior.

Remember: = assigns; == compares. A strong answer contrasts purpose, syntax, effect and use in a condition rather than merely counting equals signs.

U.2-T.0.4 | Theory | 20-Mark Preparation

Explain and, or and not with examples.

Logical operators combine or invert truth conditions. False, None, numeric zero and empty collections are falsey; most other objects are truthy. The operators are especially useful in if and while conditions.

Key explanation

1. and. For boolean operands, and is True only when both operands are True. In A and B, Python returns A if A is falsey; otherwise it evaluates and returns B.

2. or. For booleans, or is True when at least one operand is True. In A or B, Python returns A if A is truthy; otherwise it evaluates and returns B.

3. not. not reverses truth and always returns a bool. not True is False, and not [] is True because an empty list is falsey.

4. Truth table. For (A,B) = (False,False), (False,True), (True,False), (True,True), A and B is False, False, False, True; A or B is False, True, True, True.

5. Short-circuiting and precedence. and skips its second operand when the first is falsey; or skips it when the first is truthy. This can guard operations such as division. not binds more tightly than and, and more tightly than or.

Python 3 code / example

: Code summary: This code demonstrates the behavior of Python's logical operators and short-circuit evaluation. It first tests basic boolean logic using age and identification status to determine access eligibility. It then illustrates short-circuiting by attempting a division by zero that is skipped because the preceding and-condition is false. Finally, it shows how the and and or operators return the value of one of the operands rather than a simple boolean when applied to non-boolean types.

Expected output

Code summary: This sequence of values consists of two boolean true flags, two boolean false flags, the string Guest, and the integer 7.

Explanation of the example

The guarded division is never evaluated because x != 0 is false. The last two expressions demonstrate operand-returning behavior: or selects Guest after an empty string, and and returns 7 after a truthy string. Therefore it is inaccurate to say and and or always return True or False.

Logical operators express combined conditions and allow efficient conditional evaluation. Explain both their boolean truth tables and short-circuit behavior.

U.2-T.0.5 | Theory | 20-Mark Preparation

Explain membership operators in and not in.

Membership operators test whether a value belongs to a container or iterable. in returns True when membership is found; not in returns the opposite result. The exact meaning depends on the container type.

Key explanation

1. Lists and tuples. Membership checks whether any element compares equal to the target. 20 in [10, 20, 30] is True; 40 not in (10, 20, 30) is True. This checks values, not indexes.

2. Strings. Membership tests a substring, not only one character. "thon" in "Python" is True. It is case-sensitive, so "python" in "Python" is False.

3. Dictionaries. Membership normally checks keys. In {"name": "Anu"), "name" in d is True, but "Anu" in d is False. Use d.values() to test values.

4. Sets. Sets support membership using hashing and equality. They are useful for repeated tests against many distinct allowed values. Set and dictionary key membership are average O (1); list and tuple membership can require O (n) scans.

5. Negation and boundaries. x not in collection is clearer than not (x in collection), though both express non-membership. Membership in an empty collection is false. The empty string is a substring of any string.

Python 3 code / example

Code summary: This code demonstrates the use of membership operators to verify if specific elements exist within various Python data structures, including checking for integers in a list, substrings within strings, and the presence of keys and values within a dictionary.

Expected output

Code summary: This sequence of boolean values represents a series of truth evaluations or flags, resulting in a final set of seven logical outputs.

Explanation of the example

The string examples demonstrate substring matching and case sensitivity. The dictionary examples show why testing a value requires a values view. Membership does not modify the collection. Use it directly for yes/no questions instead of calculating a position with find() or index().

in and not in provide readable containment tests. Always state whether the container holds elements, substrings or dictionary keys.

U.2-T.0.6 | Theory | 20-Mark Preparation

Explain identity operators is and is not.

Identity operators determine whether two references denote the very same object. a is b returns True for one shared object; a is not b returns its negation. This differs from equality, which compares values through ==.

Key explanation

1. Identity versus equality. Two separately created lists [1, 2] may compare equal but are distinct objects. Their == comparison is True and their is comparison is False.

2. Aliasing. After b = a, both names refer to one object, so a is b is True. Mutating a shared mutable object through one name is visible through the other.

3. Copies. A list copy with a.copy() creates a different outer list. It may have equal contents, but its identity differs. A shallow copy can still share nested objects.

4. Singleton checking. Use value is None or value is not None when testing for the None singleton. Identity is appropriate because the test asks whether this special object was supplied.

5. Avoid value comparisons with is. Do not use is to compare ordinary numbers or strings. Implementations may reuse some immutable objects, producing misleading results. Use == for a required value and is for a required object identity.

Python 3 code / example

Code summary: This code snippet demonstrates the fundamental difference between value equality and object identity in Python. By comparing two identical lists and a reference to one of those lists, it illustrates that while two distinct objects can be equal in value, only objects referring to the same memory location are identical. It further shows that mutating a referenced object affects all variables pointing to that memory address and confirms the use of the identity operator to check for null values.

Expected output

True

False

True

[1,2,3]

True

True

Explanation of the example

a and b begin with equal contents but refer to independently created lists. c aliases a, so appending through c changes the object seen through a. b remains [1, 2]. The final test is the standard way to check for a missing result represented by None.

Equality asks whether values match; identity asks whether references point to one object. This distinction is central to understanding aliases and mutation.

U.2-T.0.7 | Theory | 20-Mark Preparation

Explain bitwise operators with an example.

Bitwise operators manipulate individual binary digits of integers. They are useful for flags, masks and low-level numerical operations. For clear examples, take a = 5 (0101 in four displayed bits) and b = 3 (0011).

Key explanation

1. and & and or |. and sets a bit only when both input bits are 1: 0101 & 0011 = 0001, so 5 & 3 = 1. or sets a bit when either is 1: 0101 | 0011 = 0111, so 5 | 3 = 7.

2. xor ^. Exclusive or sets a bit when the two bits differ: 0101 ^ 0011 = 0110, so 5 ^ 3 = 6. The operator ^ is not exponentiation; Python uses ** for powers.

3. Complement ~. ~x in Python integers equals -x - 1, so approximately 5 is -6. Python does not restrict integers to the four displayed bits; do not claim approximately 5 is simply the positive binary 1010.

4. Left shift <<. a << k shifts left by k positions and equals a multiplied by 2 ** k for nonnegative k. 5 <less than 1 is 10, displayed as binary 1010.

5. Right shift >>. a >> k shifts right and equals floor division by 2 ** k. 5 >greater than 1 is 2. A negative shift count raises ValueError.

6. Logical distinction. Bitwise operators operate on integer representations; and, or and not perform truth testing and short-circuit evaluation. These operations are not interchangeable.

Python 3 code / example

Code summary: This sequence demonstrates basic bitwise operations in Python using two integers. It performs a bitwise AND, OR, XOR, and NOT to manipulate specific bits, followed by left and right bit-shifts to multiply or divide the value by powers of two, and finally uses a mask to check if the number is odd or even.

Expected output

Explanation of the example

The final expression masks every bit except the least significant bit. Its result is 1 for an odd integer and 0 for an even integer. Masks can similarly test whether a particular flag is enabled. Binary columns help demonstrate how each operator produces its decimal result.

Explain each symbol with binary working and its decimal answer. Pay special attention to complement behavior and the difference between ^ and **.

U.2-T.0.8 | Theory | 20-Mark Preparation

Explain if, if-else and nested if with syntax and examples.

Conditional statements choose which block to execute based on a truth test. A colon ends each header, and indentation identifies its block. Python allows a single branch, a two-way choice and decisions inside other decisions.

Key explanation

1. Simple if syntax. if condition: followed by an indented block. The block runs only when the condition is truthy. If the condition is falsey, execution continues after the block.

2. if-else syntax. if condition: has a true block; else: introduces the alternative block at the same indentation as if. Exactly one of the two branches runs for each visit to the statement.

3. Nested if syntax. An inner if appears inside an outer branch. Its header and body are indented one additional level. The inner condition is reached only when execution enters the containing branch.

4. Suitable uses. A simple if can display a warning. if-else can decide pass or fail. A nested if can check eligibility first and then check a second requirement such as identification.

5. Correctness and readability. Use comparisons such as == and >= in conditions. Do not confuse = with ==. Keep related else clauses aligned with the if they belong to and avoid unnecessary nesting when a combined condition is clearer.

Python 3 code / example

Code summary: This script demonstrates various conditional logic structures to evaluate user eligibility and performance. It first uses a simple threshold to determine if a passing grade is achieved, follows with a two-way decision to distinguish between high performance and other results, and concludes with a nested check to ensure both age and identification requirements are met before allowing entry.

Expected output

: Code summary: This procedure validates whether a set of entry requirements—specifically a pass condition and a distinction threshold—have been met to determine if entry is allowed.

Explanation of the example

75 satisfies the first condition but not the distinction condition. For entry, the outer age test succeeds, so the inner identification test is reached and succeeds. If age were 16, only the outer else would run; the inner test would not be evaluated.

Use if for an optional action, if-else for two alternatives and nested if when one decision depends on entering another branch.

U.2-T.0.9 | Theory | 20-Mark Preparation

Explain the if-elif-else ladder.

An if-elif-else ladder selects one branch from several alternatives. Python tests conditions in written order and executes only the first truthy branch. The final else is optional and handles the case where none of the earlier conditions succeeds.

Key explanation

1. Syntax. Begin with if condition1:, follow with one or more elif condition2: blocks and optionally finish with else:. All branch headers align; their bodies are indented.

2. Evaluation. Once a condition succeeds, later conditions are skipped. The ladder is therefore different from several independent if statements, which may all run.

3. Ordering. Overlapping ranges must be ordered carefully. For grade thresholds, test the highest threshold first. Otherwise a high mark may be captured by a lower category.

4. Validation. An initial branch can reject out-of-range data before classification. For marks, numbers below 0 or above 100 should not receive a normal grade.

5. Applications. Use ladders for grades, menu choices, calculator operations or mutually exclusive classifications. The conditions need not all compare the same variable, but should form a coherent decision.

Python 3 code / example

Code summary: This procedure assigns a letter grade based on a numerical score. It first validates that the marks fall within a legitimate range of 0 to 100, then evaluates the score against a series of descending thresholds to determine the appropriate grade, ranging from A-plus for scores 90 and above down to a Fail for those below 40.

Expected output

Grade A

Explanation of the example

82 passes the validation check, fails the 90 threshold and satisfies the 75 threshold. Python prints Grade A and skips all remaining branches, even though 82 is also at least 60 and 40. Boundary values belong to the branch using >= at that threshold; for example, 75 also receives Grade A.

A ladder is a first-match decision structure. For a full answer, give syntax, explain the execution order and trace one input through the conditions.

U.2-T.1.0 | Theory | 20-Mark Preparation

Differentiate between for and while loops.

A loop repeats a block. Python for loops iterate over items from an iterable, while while loops repeat as long as a condition is truthy. Both can use break, continue, nested statements and an optional else block.

Key explanation

1. Control mechanism. for item in iterable: obtains the next item automatically. while condition: reevaluates a condition before every iteration. Neither body runs if there is no first item or the initial condition is false.

2. Typical use. for is natural for traversing a list, string, dictionary or range. while is natural when repetition depends on changing state, a sentinel value or an unknown number of attempts.

3. Initialization and progress. A for loop manages iterator advancement. A while loop usually requires explicit initialization and an update or another event that makes its condition false. Missing that progress can cause an infinite loop.

4. Counting. range() makes a for loop convenient for known counts. The same computation can be expressed with while by maintaining a counter. A for loop is not limited to cases where the count is known in advance; generators can produce items dynamically.

5. Loop controls and else. break exits the nearest loop, continue starts its next iteration, and else runs on normal completion without break. In a while loop, ensure necessary updates are not accidentally skipped by continue.

Python 3 code / example

Code summary: This procedure demonstrates two different ways to calculate the sum of integers from 1 to 5. It first uses a for loop to iterate through the range and then uses a while loop with a manual counter to achieve the same result, ultimately printing the total sum for each method.

Expected output

Code summary: This procedure iterates through a fixed sequence of 15 cycles, executing a repetition loop 15 times to perform a repetitive task.

Explanation of the example

Both loops add 1 + 2 + 3 + 4 + 5 . The for loop receives the next value from range. The while loop controls its own number variable and terminates after it becomes 6. Removing number += 1 would repeatedly add 1 without terminating.

Choose for when the task is expressed as visiting items, and while when it is expressed as continuing until a condition changes.

U.2-T.1.1 | Theory | 20-Mark Preparation

Explain range() with examples.

range() represents an immutable arithmetic sequence of integers. It is often used to control a for loop. A range stores its bounds and step compactly instead of materializing all its values as a list.

Key explanation

1. One argument. range (stop) begins at 0 and advances by 1, excluding stop. range (5) therefore represents 0, 1, 2, 3, 4.

2. Two arguments. range (start, stop) begins at start and advances by 1. range (2, 6) represents 2, 3, 4, 5. The stop value is never included.

3. Three arguments. range (start, stop, step) changes by step each time. range (2, 11, 2) gives 2, 4, 6, 8, 10. The default step is 1.

4. Negative step. A negative step counts downward. range(5, 0, -1) gives 5, 4, 3, 2, 1. If the bounds and direction are inconsistent, the range is empty.

5. Restrictions and operations. A zero step raises ValueError. Arguments must be integers or support the integer-index protocol; ordinary floats are not accepted. Ranges support iteration, indexing, slicing, membership and len(). Use list(range(...) when an actual list is required.

Python 3 code / example

Code summary: This code demonstrates the functionality of the range function in Python by generating sequences of integers. It showcases different configurations, including starting from zero, specifying a custom start and stop point, using a step value to create an incrementing sequence, and utilizing a negative step to create a descending sequence. It concludes by using a for loop to iterate through and print a sequence of three integers.

Expected output

Code summary: This code block defines a series of integer lists of varying lengths—including one empty list—followed by a sequence of three standalone integers.

Explanation of the example

The empty result occurs because a positive default step cannot move from 5 toward a lower stop of 0. To include an upper bound n while counting upward by one, use range(1, n + 1). The printed list is a materialized representation; the range itself remains a compact sequence object.

Remember start inclusive, stop exclusive and step nonzero. These rules prevent most range-related off-by-one errors.

U.2-T.1.2 | Theory | 20-Mark Preparation

Explain tuple unpacking in a for loop.

Tuple unpacking assigns the elements of a sequence to separate target names. In a for loop, each item produced by the iterable is unpacked on each iteration. The item need not literally be a tuple; any suitable iterable can be unpacked.

Key explanation

1. General syntax. for first, second in collection: expects each item to yield two values. The loop assigns those values to first and second before executing the body.

2. Records. A list such as [("Anu", 80), ("Ravi", 90)] stores two-field records. Unpacking gives meaningful names without repeatedly writing record [0] and record [1].

3. Dictionary pairs. for key, value in dictionary.items(): unpacks each mapping entry. Iterating directly over the dictionary yields keys only, not key-value pairs.

4. Index and item. for index, value in enumerate(sequence): unpacks the index-value pairs from enumerate(). An optional start argument controls the initial index label.

5. Arity and starred targets. Without a starred target, the number of targets must match the number of values, otherwise ValueError occurs. A starred target such as first, *rest can collect remaining values into a list.

Python 3 code / example

Code summary: This script demonstrates three ways to iterate over different data structures in Python to display paired information. It first handles a list of tuples to link student names with their marks, then uses a dictionary's items method to associate product names with prices, and finally employs the enumerate function to pair characters in a string with their 1-based positions.

Expected output

Code summary: This script contains a series of unstructured data entries, including names paired with scores, objects paired with values, and numeric keys paired with alphabet characters.

Explanation of the example

On the first student iteration, name becomes Anu and marks becomes 80. The next iteration replaces them with Ravi and 90. The dictionary loop uses items() to obtain exactly two values per entry. enumerate supplies a running position alongside each character.

Unpacking makes structured iteration readable. State the expected shape of each item and explain the error caused by mismatched numbers of targets and values.

U.2-T.1.3 | Theory | 20-Mark Preparation

Explain the while-else construct.

A while statement can have an else block aligned with the while header. The else block runs when the loop finishes normally because its condition becomes false. It does not run when the loop is exited through break.

Key explanation

1. Syntax. while condition: contains an indented body; else: follows at the same indentation as while and contains its own body. The else belongs to the loop, not to an if inside it.

2. Normal termination. If repeated updates eventually make the condition false, else executes. It also executes if the condition is false on the first test and the body never runs.

3. Early termination. break skips the loop else. A return from the containing function or a propagating exception also prevents reaching else. continue alone does not suppress else.

4. Search application. Use the body to search for a match and break when found. Put the no-match message in else. This avoids a separate found flag when the structure remains clear.

5. Common misconception. The else does not mean the loop condition was always false, nor does it run after every iteration. It describes completion without a break.

Python 3 code / example

Code summary: This procedure performs a linear search through a list of numbers to find the index of a specific target value. It iterates through the list sequentially, terminating early if a match is found; otherwise, it executes a fallback block to notify the user that the target is not present.

Expected output

Not found

Explanation of the example

The program checks indexes 0, 1 and 2. None contains 5, so i becomes 3 and the condition becomes false. The else then prints Not found. If target were 7, the match at index 1 would print Found at index 1 and execute break, skipping else.

The best memory aid is: a loop else runs on normal completion without break. Demonstrate both a found and a not-found path when explaining it in an exam.

U.2-T.1.4 | Theory | 20-Mark Preparation

Explain break, continue and pass.

These statements have very different effects. break terminates a loop, continue skips the remaining statements in the current iteration, and pass performs no action. Indentation and placement determine what each statement affects.

Key explanation

1. break. Immediately exits the nearest enclosing for or while loop. Execution continues after that loop, and its else block is skipped. In nested loops, break does not automatically exit all loops.

2. continue. Skips the remainder of the current iteration and proceeds to the next loop step or condition test. It does not terminate the loop. In a while loop, place necessary updates so they are not skipped.

3. pass. A null statement used where syntax requires a statement but no action is currently needed. It can be used in a class, function, branch or loop body. It does not skip subsequent statements.

4. Appropriate uses. Use break when a search succeeds, continue to ignore unwanted input items, and pass for an intentionally empty syntactic block. break and continue must occur within a loop context.

5. Comparison. break changes loop termination; continue changes the current iteration; pass changes nothing. Replacing one with another can radically alter results or cause nontermination.

Python 3 code / example

: Code summary: This code demonstrates the distinct behaviors of three Python control flow statements within loops. The first loop uses a break statement to terminate the process entirely when a specific condition is met. The second loop uses a continue statement to skip a single iteration and move to the next. The third loop uses a pass statement as a placeholder that allows the loop to continue without performing any specific action for that iteration. The final output is three separate lines of numbers reflecting these different execution paths.

Expected output

Code summary: This block contains a sequence of three numeric values, 12, 1245, and 123, printed on separate lines.

Explanation of the example

The first loop stops entirely at 3. The second skips printing 3 but resumes with 4 and 5. In the third loop, pass does nothing when i is 2, so the following print still runs. This side-by-side output demonstrates the behavioral distinction.

Explain each statement through its control-flow effect. pass is not a synonym for continue, and break affects only the nearest loop.

U.2-T.1.5 | Theory | 20-Mark Preparation

Explain nested loops with an example.

A nested loop is a loop placed inside another loop. For each iteration of the outer loop, execution enters the inner loop, which can perform several iterations. Nested loops naturally process rows and columns, combinations and patterns.

Key explanation

1. Execution order. The outer loop selects one value, then the inner loop processes its values before the next outer iteration. For independent counts m and n, the body executes m times n times.

2. Syntax and indentation. The inner loop header is indented inside the outer body, and the inner body is indented another level. Statements after the inner loop but still inside the outer loop run once per outer iteration.

3. Applications. Examples include multiplication tables, matrix traversal, star patterns and comparing pairs. The loops may be for-for, while-while or mixed.

4. Loop controls. break exits only the closest loop. continue applies to the closest loop that contains it. Exiting multiple levels requires additional logic or a suitable function structure.

5. Complexity. Two loops each visiting n values commonly take O(n squared) time, but nesting alone does not determine complexity. Bounds may be constant, unequal or dependent on the outer variable.

Python 3 code / example

: Code summary: This procedure generates a 3-by-3 multiplication table by iterating through rows and columns from 1 to 3, calculating the product of the current indices, and printing them in a grid format.

Expected output

Code summary: This numerical matrix represents a multiplication table or a simple linear transformation where each row corresponds to a multiplier, and each column corresponds to a multiplicand, resulting in a three-by-three grid of products.

Explanation of the example

For row = 1, the inner loop visits columns 1, 2 and 3 and prints 1, 2 and 3. The outer-body print() then ends the line. Rows 2 and 3 repeat the inner sequence with their own products. There are 3 times 3 = 9 product prints and three newline calls. Moving the newline into the inner body would put each product on a separate line.

Use the outer loop for a larger unit such as a row and the inner loop for its elements. A trace table of outer and inner values makes nested execution easy to explain.

U.2-P.0.1 | Programming | 20-Mark Preparation

Check whether a number is prime.

A prime number is an integer greater than 1 having exactly two positive divisors: 1 and itself. If a composite number has a factor greater than its square root, the paired factor is smaller, so testing divisors only up to the square root is sufficient.

Algorithm

1. Input and initialization. Read integer n. Initially regard it as prime only if n >= 2.

2. Trial division. Start divisor at 2 and test while divisor * divisor <= n and the prime flag remains true.

3. Detect a factor. If n % divisor is zero, mark the number as not prime. Otherwise move to the next divisor.

4. Report. Print the classification using the final flag.

Python 3 code / example

Code summary: This procedure determines if a user-provided integer is a prime number. It first establishes a baseline check that the number must be at least 2, then iteratively tests for divisors starting from 2. To optimize performance, the search stops once the divisor exceeds the square root of the input, as any larger factor would have a corresponding smaller factor already checked. The process concludes by printing whether the number is prime or not based on whether any divisors were found.

Code summary: This procedure takes a sample input, specifically the number 29, and processes it to provide a result.

Expected output

Prime

Dry run and correctness

For 29, divisors 2, 3, 4 and 5 leave remainders. The next divisor is 6 and 6 times 6 exceeds 29, so the loop ends with is prime still True. For 25, divisor 5 gives remainder zero, changing the flag to False. The <= boundary is important for detecting squares such as 25.

Edge cases and exam notes

Negative integers, 0 and 1 are not prime. The number 2 is prime and needs no loop iterations. Multiplying divisor by itself avoids floating-point square-root rounding. The flag prevents further divisor testing after a factor is found.

O (sqrt(n)) trial divisions for n >= 2 in the worst case and O (1) auxiliary space, using the usual unit-cost arithmetic model.

U.2-P.0.2 | Programming | 20-Mark Preparation

Check whether a number is an Armstrong number.

A nonnegative integer is an Armstrong number when it equals the sum of its decimal digits each raised to the number of digits. For a three-digit number such as 153, the condition is 1 cubed + 5 cubed + 3 cubed = 153. The general definition also applies to other digit counts.

Algorithm

1. Validate. Read an integer and reject negative input.

2. Count digits. Convert the nonnegative number to text and obtain its length. Zero has one digit.

3. Accumulate powers. For each digit character, convert it to an integer and add digit times digit count to total.

4. Compare. If total equals the original number, report Armstrong number; otherwise report the opposite.

Python 3 code / example

Code summary: This procedure determines if a given nonnegative integer is an Armstrong number. It first validates that the input is nonnegative, then calculates the sum of each digit raised to the power of the total number of digits. Finally, it compares this sum to the original number to output whether the input satisfies the Armstrong number criteria.

Sample input (in prompt order): 153

Expected output

Armstrong number

Dry run and correctness

The string "153" has length 3. The terms are 1 raised to the power of 3 equals 1, 5 raised to the power of 3 equals 125 and 3 raised to the power of 3 equals 27. Their sum is 153, equal to n. For 154, the sum is 1 plus 125 plus 64 equals 190, so the test fails. A four-digit example is 1634 equals 1 raised to the power of 4 plus 6 raised to the power of 4 plus 3 raised to the power of 4 plus 4 raised to the power of 4.

Edge cases and exam notes

Zero is accepted because 0 superscript ** 1 = 0. Every single-digit nonnegative integer satisfies the definition. Do not always cube digits unless the question explicitly limits input to three-digit numbers. Integer conversion removes leading zeros, so the definition applies to the numeric value.

O(d) digit iterations and O(d) space for the digit string, where d is the decimal digit count. Actual bit complexity also depends on exponentiation and large integer sizes.

U.2-P.0.3 | Programming | 20-Mark Preparation

Print the Fibonacci series up to n terms.

The Fibonacci sequence starts with 0 and 1, and each later term equals the sum of the previous two. Here n means the number of terms, not an upper limit on their values. For n = 7, the sequence is 0, 1, 1, 2, 3, 5, 8.

Algorithm

1. Input and validation. Read n. Reject a negative term count; report no terms when n is zero.

2. Initialize. Set a = 0 and b = 1, representing the current and next term.

3. Repeat. For n iterations, print a and then update a, b = b, a + b.

4. Finish. Print a final newline after the series.

Python 3 code / example

Code summary: This procedure generates the Fibonacci sequence up to a user-specified number of terms. It first validates that the input is a nonnegative integer to handle invalid or empty requests. If valid, it uses an iterative loop to compute and print each term by continuously summing the two most recent values, starting from 0 and 1, until n terms have been displayed.

Sample input (in prompt order): 7

Expected output

0112358

Dry run and correctness

The pairs before successive prints are (0, 1), (1, 1), (1, 2), (2, 3), (3, 5), (5, 8), (8, 13). Each iteration prints the first value and shifts the pair forward. Parallel assignment uses the old a and b for both right-hand expressions. Sequential a = b; b = a + b would incorrectly use the updated a.

Edge cases and exam notes

n = 1 prints only 0; n = 2 prints 0 and 1. Zero produces no numeric terms. The code prints directly instead of storing a growing list. Fibonacci conventions sometimes begin 1, 1; this answer explicitly uses the common 0, 1 convention.

O (n) additions and O (1) stored integer variables. Fibonacci values grow, so actual arithmetic time and the bits required for those integers increase with n.

U.2-P.0.4 | Programming | 20-Mark Preparation

Calculate factorial using a loop.

The factorial of a nonnegative integer n is the product 1 times 2 times through n, written n factorial. By definition, 0 factorial equals 1. Factorial is not defined by this elementary product for negative integers.

Algorithm

1. Read and validate. Read n and reject negative input.

2. Initialize product. Set factorial = 1, the multiplicative identity.

3. Multiply. For every integer from 2 through n inclusive, multiply factorial by that integer.

4. Display. Print the final product.

Python 3 code / example

Code summary: This procedure calculates the factorial of a user-provided integer. It first validates that the input is non-negative, as factorials are undefined for negative numbers. For valid inputs, it uses an iterative loop to repeatedly multiply integers from 2 up to the target number, ultimately producing and printing the final product.

Sample input (in prompt order): 5

Expected output

Factorial: 120

Dry run and correctness

The product begins at 1. Multiplying by 2 gives 2, by 3 gives 6, by 4 gives 24 and by 5 gives 120. After the iteration for number k, factorial equals k!. This invariant starts correctly and is preserved by multiplying the previous factorial by k. The upper bound n + 1 ensures that n is included.

Edge cases and exam notes

For n = 0 or n = 1, the range is empty and the initialized value 1 is correct. Initializing the product to zero would incorrectly make every result zero. Python integers can grow beyond fixed-width machine integer limits, but very large factorials still consume substantial resources.

O (n) multiplications and O (1) integer variables. This operation count treats arithmetic as unit cost; actual multiplication cost and result storage grow with the number of digits in n!.

U.2-P.0.5 | Programming | 20-Mark Preparation

Check whether a year is a leap year.

Under the Gregorian calendar rule, a year is a leap year if it is divisible by 400, or if it is divisible by 4 but not by 100. A leap year has 366 days rather than 365. This program applies that rule to positive integer year numbers.

Algorithm

1. Validate input. Read the year and reject zero or negative values for this civil-year convention.

2. Apply century exception. A multiple of 400 is a leap year even though it is also a multiple of 100.

3. Apply ordinary rule. A multiple of 4 is a leap year only if it is not a multiple of 100.

4. Report. Combine the conditions with or and and, then print the result.

Python 3 code / example

Code summary: This procedure determines if a given input year is a leap year. It first validates that the year is a positive integer and then applies the standard Gregorian calendar rules—checking if the year is divisible by 400 or divisible by 4 but not by 100—to output whether the year is a leap year or not.

Sample input (in prompt order): 2000

Expected output

Leap year

Dry run and correctness

For 2000, divisibility by 400 is true, so it is a leap year. For 1900, divisibility by 400 is false and the not-divisible-by-100 requirement is false, so it is not a leap year. For 2024, the year is divisible by 4 but not by 100, so it is a leap year. For 2023, neither route succeeds.

Edge cases and exam notes

Check century years explicitly: 1900 and 2100 are not leap years, whereas 2000 and 2400 are. Testing only year %4 == 0 is incomplete. Historical local calendar adoption is outside this programming exercise; the stated Gregorian rule is applied uniformly.

O arithmetic tests and O auxiliary space under the usual fixed-size input model.

U.2-P.0.6 | Programming | 20-Mark Preparation

Print the multiplication table of an entered number.

A multiplication table lists the products of a chosen number with consecutive multipliers. This solution prints multipliers 1 through 10, the usual exam convention. Each line displays the multiplication expression and its result.

Algorithm

1. Read. Accept an integer n.

2. Iterate. Use range (1, 11) to generate all ten multipliers, including 10.

3. Compute and display. For each multiplier, compute n * multiplier and print a labeled equation.

Python 3 code / example

Code summary: This procedure generates a multiplication table for a user-provided integer. It prompts for an input value and then iterates through a range of multipliers from 1 to 10 to calculate and display each product.

Sample input (in prompt order): 7

Expected output

Code summary: This sequence calculates the first ten multiples of 7 by incrementally multiplying the base value of 7 by integers from 1 to 10, resulting in a list of products ranging from 7 to 70.

Dry run and correctness

The multiplier starts at 1, producing 7. Each iteration increases it by one, so the products increase by 7. The final multiplier is 10 and the last product is 70. The range stop is 11 because Python excludes the stop value. The loop body executes exactly once for every required table line.

Edge cases and exam notes

Zero produces ten zero products. Negative integers produce negative products for these positive multipliers. The program assumes valid integer input. To print up to a user-specified positive limit m, read m and replace range (1, 11) with range (1, m + 1).

For the fixed ten-line table, O time and O auxiliary space. For a generalized table of m rows, O (m) time and O auxiliary space, excluding output.

U.2-P.0.7 | Programming | 20-Mark Preparation

Find the sum of the digits of a number.

The digit sum adds the decimal digits of a number without regard to place value. For example, 472 has digit sum 4 + 7 + 2 = 13 . This solution ignores a negative sign by processing the absolute value.

Algorithm

1. Initialize. Read n, set remaining = abs(n), and set total = 0.

2. Extract last digit. Use remaining % 10 to obtain the rightmost decimal digit.

3. Accumulate and shorten. Add that digit to total, then remove it with remaining norm of equals 10.

4. Repeat and report. Continue until remaining becomes zero, then print total.

Python 3 code / example

Code summary: This procedure calculates the sum of the individual digits of a user-provided integer. It first ensures the number is positive by taking its absolute value, then enters a loop that repeatedly extracts the last digit using the modulo operator and removes it using floor division. This process continues until all digits have been processed and added to a running total, which is then printed as the final result.

Sample input (in prompt order): 472

Expected output

Digit sum: 13

Dry run and correctness

The states (remaining, digit, total after addition) are (472,2,2), (47,7,9) and (4,4,13). Integer division removes the digit already counted. The loop maintains that total is the sum of removed digits, while remaining contains exactly the digits not yet processed. Thus total is the full digit sum at termination.

Edge cases and exam notes

For 0, the loop does not run and the result is correctly zero. For -472, abs() gives 472 and the result is 13. Using / instead of // would produce floating-point values and break the digit-removal algorithm. Taking abs() also avoids difficulties with floor division of negative numbers.

O (d) iterations for d decimal digits and O (1) integer variables. For positive n, d is floor (log10(n)) + 1; zero is treated separately.

U.2-P.0.8 | Programming | 20-Mark Preparation

Reverse a number using a while loop.

Reversing an integer places its last digit first and its first digit last. The algorithm extracts the last digit and appends it to a growing reversed value. This answer preserves the sign of negative input and treats the result as a number, so leading zeros disappear.

Algorithm

1. Initialize. Read n, process absolute value of n, and initialize reversed number to zero.

2. : Extract and append. Get digit equals remaining modulo 10 and set reversed number equals reversed number times 10 plus digit.

3. Remove processed digit. Apply remaining norm of equals 10 and repeat until no digits remain.

4. Restore sign. Negate the result if the original input was negative, then display it.

Python 3 code / example

Code summary: This procedure reverses the digits of a user-provided integer. It first works with the absolute value of the input to isolate each digit using modulo and integer division, building the reversed number incrementally. Finally, it restores the original sign of the integer before returning the reversed result.

Sample input (in prompt order): 1234

Expected output

Reversed: 4321

Dry run and correctness

The successive reversed values are 4, 43, 432 and 4321, while remaining becomes 123, 12, 1 and 0. Multiplication by 10 shifts the existing result left by one decimal place before the next digit is added. Every iteration moves one digit from the end of the unprocessed number to the end of the result.

Edge cases and exam notes

Zero yields zero. The input 1200 yields 21, because the reversed digit text 0021 represents the integer 21. The input -120 yields -21 under the stated sign-preserving convention. If leading zeros must be displayed, the required result is a string representation rather than an integer.

O (d) iterations and O integer variables for d digits; the reversed result itself needs O (d) digits of storage.

U.2-P.0.9 | Programming | 20-Mark Preparation

Print primes between 1 and 100 using nested loops.

The program tests each candidate from 2 through 100. An outer loop selects a candidate, and an inner loop searches for a divisor. A candidate is printed only if the search finishes without finding any divisor.

Algorithm

1. Outer loop. Generate candidates with range (2, 101); 1 is excluded because it is not prime.

2. Inner loop. Test possible divisors from 2 up to the candidate minus one.

3. Break on a factor. If candidate % divisor == 0, break from the inner loop.

4. Print on normal completion. Attach else to the inner for loop. It prints the candidate only if no break occurred.

Python 3 code / example

Code summary: This procedure identifies and prints all prime numbers between 2 and 100. It iterates through each candidate integer in that range and attempts to find a divisor; if no divisor is found before reaching the candidate's own value, the number is confirmed as prime and output to the console.

Sample input (in prompt order): No keyboard input; data is included in the program.

Expected output

Code summary: This sequence consists of the first twenty-five prime numbers, concatenated into a single string, representing the fundamental building blocks of natural numbers.

Dry run and correctness

For 2, the inner range is empty and its else prints 2. For 4, divisor 2 divides exactly, so break suppresses the else. For 5, divisors 2, 3 and 4 all fail, so the inner loop ends normally and prints 5. The else aligns with the inner for, not with the if or outer for.

Edge cases and exam notes

There are 25 primes in the displayed interval. Including range (2, 101) tests the upper endpoint 100, although it is rejected. This deliberately simple divisor range makes the nested-loop behavior clear. Testing only divisors up to the square root is a valid optimization.

For a generalized upper bound N, this implementation has an O (N squared) upper bound on trial divisions and O auxiliary space. The fixed 1 to 100 problem has a fixed amount of work.

U.2-P.1.0 | Programming | 20-Mark Preparation

Print a pyramid of stars with n rows.

A centered star pyramid has one star in the first row, three in the second, five in the third and so on. For row r numbered from 1, print n-r leading spaces followed by 2*r-1 stars. Use a monospaced display to preserve alignment.

Algorithm

1. Input and validation. Read n and require a positive number of rows.

2. Row loop. For each row from 1 through n, calculate the number of spaces and stars.

3. Construct. Use string repetition to create the leading padding and star segment.

4. Print. Join the two strings and print one completed row per iteration.

Python 3 code / example

Code summary: This procedure generates a centered pyramid pattern of stars based on a user-provided number of rows, n. After validating that n is a positive integer, it iterates through each row to calculate the necessary leading whitespace and the odd number of stars required to maintain a symmetric triangle shape, ultimately printing the formatted pattern to the console.

Sample input (in prompt order): 4

Expected output

Code summary: This code block contains only placeholder asterisks and does not implement a functional algorithm or procedure.

Dry run and correctness

For n = 4, the (spaces, stars) pairs are (3, 1), (2, 3), (1, 5) and (0, 7). Each next row removes one leading space and adds two stars, so the center stays aligned. The bottom row has width 2*n-1 = 7 . The number of stars is 1 + 3 + 5 + 7 = 16 = n squared.

Edge cases and exam notes

n = 1 prints one star. Nonpositive row counts receive a message. This is a solid centered pyramid, not a left-aligned triangle or a hollow pyramid. Trailing spaces are unnecessary. Nested character loops can replace string repetition, but repetition expresses the same row construction directly.

O(n squared) time to construct and print the characters across all rows, and O(n) temporary space for one row. There are n loop iterations but a growing amount of output per iteration.

U.2-P.1.1 | Programming | 20-Mark Preparation

Find the G.C.D of Two Numbers Using a While Loop.

The greatest common divisor is the greatest nonnegative integer that divides both inputs. Euclid's algorithm uses gcd(a,b) = gcd(b,a % b) for b not equal to zero. Replacing the pair repeatedly reduces the problem until the second value becomes zero.

Algorithm

1. Normalize. Read two integers and take their absolute values.

2. Reduce. While b is nonzero, simultaneously replace a with b and b with a % b.

3. Terminate. When b is zero, a is the G.C.D.

4. Output. Print the final nonnegative result. Use gcd (0, 0) = 0 as the program convention.

Python 3 code / example

Code summary: This procedure calculates the greatest common divisor of two user-provided integers. It first ensures both inputs are non-negative using absolute values, then iteratively applies the Euclidean algorithm—repeatedly replacing the larger number with the remainder of the two—until the remainder is zero, returning the final non-zero value as the GCD.

Sample input (in prompt order): 48 | 18

Expected output

G.C.D: 6

Dry run and correctness

The successive pairs are (48, 18), (18, 12), (12, 6) and (6, 0). Thus the result is 6. The invariant is that the G.C.D of the current pair equals that of the original pair: any common divisor of a and b also divides a - q*b, their remainder, and the converse holds. The nonnegative remainder is smaller than b, ensuring termination.

Edge cases and exam notes

If one input is zero, the result is the absolute value of the other. For both zero, the code returns the common programming convention 0; elementary definitions may leave that case undefined. Negative signs do not affect divisibility after normalization. Parallel assignment is necessary so a % b uses the old pair.

O (log(min(a,b))) remainder steps for positive inputs, with zero cases handled immediately; O (1) integer variables. Large-integer remainder cost is additional to this step count.

U.2-P.1.2 | Programming | 20-Mark Preparation

Check whether a number is perfect.

A perfect number is a positive integer equal to the sum of its positive proper divisors, excluding itself. For example, 6 is perfect because its proper divisors are 1, 2 and 3, whose sum is 6.

Algorithm

1. Validate. Read n. Values less than or equal to 1 are not perfect.

2. Accumulate divisors. Initialize divisor sum to zero. Test integers from 1 through n // 2, because no proper positive divisor of n can be larger than n/2.

3. Add matches. If n % divisor is zero, add the divisor to the sum.

4. Compare. Report perfect if the final sum equals n; otherwise report not perfect.

Python 3 code / example

Code summary: This procedure determines if a user-provided integer is a perfect number. It first filters out values less than or equal to 1, as they cannot be perfect. For valid inputs, it iterates through all possible divisors up to half of the number's value to calculate their sum. Based on whether this accumulated sum equals the original integer, it outputs whether the number is perfect or not.

Sample input (in prompt order): 28

Expected output

Perfect number

Dry run and correctness

The divisors accepted between 1 and 14 are 1, 2, 4, 7 and 14. Their sum is 28, so the equality test succeeds. For 12, the proper divisors 1, 2, 3, 4 and 6 sum to 16, so it is not perfect. The loop excludes n itself by stopping at half the number.

Edge cases and exam notes

1 is not perfect because its proper-divisor sum is zero. Zero and negative numbers are rejected as non-perfect by this definition. Do not confuse perfect numbers with perfect squares or Armstrong numbers. A square-root factor-pair algorithm can improve performance, but must avoid double-counting square-root factors.

O (n) trial divisions and O (1) auxiliary space. The half-range improves the constant factor but not the linear complexity class.

U.2-P.1.3 | Programming | 20-Mark Preparation

Print Pascal's triangle up to n rows.

Pascal's triangle starts with a row containing 1. Each subsequent row begins and ends with 1, and every interior entry is the sum of the two entries directly above it. Row r, numbered from zero, contains the binomial coefficients C(r,0) through C(r,r) .

Algorithm

1. Validate and initialize. Require a positive row count and begin with row = [1].

2. Preserve each row for display. Convert the current values to text and append the completed line to a list of lines.

3. Build the next row. Start with 1, append sums of adjacent values from the current row, and finish with 1.

4. Center output. After generating n lines, use the last line's width to center each printed line. Strip trailing padding while retaining leading padding.

Python 3 code / example

Code summary: This procedure generates and displays Pascal's Triangle for a user-specified number of rows. After validating that the row count is positive, it iteratively constructs each row by summing adjacent elements from the previous row to determine the interior values. Finally, it calculates the width of the longest row to center-align and print the resulting triangle.

Expected output

Code summary: Pascal's Triangle displays the binomial coefficients for powers of a binomial, where each entry is generated by summing the two values directly above it to represent the expansion of the expression x plus y raised to the power of n.

Dry run and correctness

From [1, 3, 3, 1], adjacent sums are 4, 6 and 4; surrounding them with endpoint ones gives [1, 4, 6, 4, 1]. This implements Pascal's recurrence directly. The generated rows have 1, 2, 3, 4 and 5 entries. Their sums are 1, 2, 4, 8 and 16, which provides a useful independent correctness check.

Edge cases and exam notes

n = 1 prints a single 1. Nonpositive input is rejected. Centering uses actual string widths, so multi-digit coefficients are retained without truncation; the output is a readable centered list of rows rather than a fixed-width cell grid. The code computes one final unused next row, which is harmless.

O(n squared) additions and O(n squared) stored entries/text fields under a unit-cost model. Large coefficients increase arithmetic and text storage costs; output itself contains n(n+1)/2 numbers.

U.2-P.1.4 | Programming | 20-Mark Preparation

Display 1 to 100, skipping multiples of 3 and 5.

This answer interprets "skipping the multiples of 3 and 5" as skipping any number divisible by 3 or by 5. Thus 3, 5, 6, 10 and 15 are all omitted. The interpretation is stated because requiring both divisibilities would omit only multiples of 15.

Algorithm

1. Generate numbers. Iterate from 1 through 100 inclusive using range (1, 101).

2. Test exclusion. Check number % 3 == 0 or number % 5 == 0.

3. Skip or print. Use continue when the exclusion condition is true. Otherwise print the number.

4. Finish. Print a newline after the sequence.

Python 3 code / example

Code summary: This procedure filters a sequence of integers from 1 to 100 to identify and print only those numbers that are not divisible by either 3 or 5.

Sample input (in prompt order): No keyboard input; data is included in the program.

Expected output

Code summary: This sequence represents a numeric data set consisting of 55 integer values, ranging from 1 to 98, appearing in ascending order.

Dry run and correctness

1 and 2 pass the test and are printed. 3 is skipped because it is divisible by 3; 5 is skipped because it is divisible by 5. 15 satisfies both but is skipped only once. continue bypasses the print and lets the for loop advance normally. The loop still examines 100, but excludes it as a multiple of 5.

Edge cases and exam notes

There are 33 multiples of 3, 20 multiples of 5 and 6 common multiples of 15 in the range. Therefore 33 + 20 - 6 = 47 numbers are excluded and 53 are printed. If the examiner explicitly means numbers divisible by both, replace or with and and explain that changed interpretation.

O (N) time for an upper bound N and O (1) auxiliary space. For the specified fixed range, exactly 100 conditions are considered.

Simulate a simple calculator using if-elif-else.

A simple calculator reads two operands and an operator, selects the requested arithmetic operation and displays the result. This program accepts +, -, * and /, uses floating-point operands, and handles division by zero and invalid operators explicitly.

Algorithm

1. Input. Read two numbers with float() and an operator string. Strip surrounding spaces from the operator.

2. Select operation. Use an if-elif-else ladder to choose addition, subtraction, multiplication or division.

3. Guard division. Before dividing, test whether the second operand is zero and display a message instead of performing the invalid operation.

4. Handle other input. Report an invalid operator in the final else. Catch ValueError if numeric conversion fails.

Python 3 code / example

Code summary: This procedure implements a basic calculator that performs arithmetic operations. It first collects two numbers and a mathematical operator from the user, using a try-except block to ensure the inputs are valid floats. It then evaluates the chosen operator to execute the corresponding addition, subtraction, multiplication, or division, specifically checking for zero in the divisor to prevent division errors. The final result or a relevant error message is then printed.

Expected output

Result: 3.0

Dry run and correctness

The operands become 12.0 and 4.0. The first three operator comparisons fail, the division comparison succeeds, and the denominator is nonzero, so 12.0 / 4.0 produces 3.0. Only the selected branch runs. For 12, 0 and /, the nested check instead prints Cannot divide by zero.

Edge cases and exam notes

The operator % is rejected because it is outside the requested four operations. Non-numeric input such as abc triggers the ValueError handler. Negative and decimal values are accepted. The intended domain is ordinary finite numbers; floating-point arithmetic can show small representation errors. This is a single-operation calculator, not an expression evaluator.

O (1) arithmetic and branch work per operation and O (1) auxiliary space, excluding input parsing and output text.