Practice · All units

Exam Prep

Syllabus-wide Python revision reference and self-checks

Exam Prep · Units 1–5

Revise the rules you need, then test your recall

Use this compact reference for theory answers and practical work. It summarizes distinctions, syntax patterns, and the named functions in the course plan. Expand a unit, try its self-check before opening the answer, and revisit the lesson or randomized quiz for hands-on practice.

Exam habit: State the rule, show a small valid example, and explain the output or edge case. For practical questions, run your code with ordinary and boundary inputs.

Unit 1

Introduction, syntax, data types, and I/O

Names, values, types, conversion, and readable output. identifier keyword input print int float str bool list tuple set dict literal constant.

Core ideas and types

Python is an interpreted, dynamically typed language. Variables are names bound to objects; assignment does not declare a fixed type. Identifiers start with a letter or underscore, followed by letters, digits, or underscores, and cannot be keywords.

int · float · complex

Numeric values

str

Immutable text in quotes

list

Ordered and mutable; [ ]

tuple

Ordered and immutable; ( )

set

Unique hashable elements; { }

dict

Key-value pairs; {key: value}

Input, conversion, and output

name = input("Name: ")  # input returns str
age = int(input("Age: "))
print("Next year:", age + 1)

Invalid integer text raises ValueError. Validate input before conversion in a complete program.

Quick self-check: why does input('Age: ') + 1 fail?

input returns str, and Python cannot add an integer to a string. Convert the input with int() first when the text represents a whole number.

Unit 2

Operators and control flow

Operator rules, decisions, repetition, and loop control. precedence arithmetic comparison logical bitwise membership identity if elif else while for range break continue pass return.

Operator precedence · higher rows bind first

OrderOperatorsExample
1Parentheses and grouping(a + b) * c
2Exponentiationa ** b (right-associative)
3Unary +, --x
4*, /, //, %a // b
5+ and -a + b
6Shifts: <<, >>n << 1
7Bitwise: &, ^, |mask & flag
8Comparisons, in, isa <= b, x in values
9notnot ready
10andvalid and active
11orguest or member

Exponentiation binds more tightly than unary minus: -2 ** 2 is -(2 ** 2), or -4. Parentheses make intent explicit.

Control-flow patterns

if score >= 80:
    print("Distinction")
elif score >= 40:
    print("Pass")
else:
    print("Retry")

for i in range(1, 5):  # 1, 2, 3, 4
    print(i)

while count < 3:
    count += 1
break

Exit the nearest loop.

continue

Skip to the next iteration.

pass

Do nothing; placeholder statement.

return

Exit a function and optionally send back a value.

Quick self-check: what is list(range(1, 6, 2))?

[1, 3, 5]. The stop value 6 is excluded, and the step is 2.

Unit 3

Lists, tuples, sets, and dictionaries

Collection behavior, operations, and choosing the right structure. list tuple set dictionary CRUD append index slice keys values mutable immutable.

Choose a structure by asking whether order, duplicates, and later updates matter.

TypeSyntaxOrdered?Mutable?Duplicates?Typical use
list[a, b]YesYesYesSequence that changes
tuple(a, b)YesNoYesFixed record
set{a, b}No positional orderYesNoUniqueness / membership
dict{key: value}Insertion orderYesKeys: noLookup by key

Common operations

items = ["pen", "book"]
items.append("ruler")  # add at end
items[0] = "pencil"    # update
del items[1]           # remove by index

student = {"name": "Mira", "mark": 91}
student["mark"] = 95
print(student.get("email", "not supplied"))
Quick self-check: what does 'name' in a dictionary test?

It checks whether 'name' is a key. Use values() to check values.

Unit 4

Built-ins, functions, recursion, and files

Function signatures, return values, recursion, scope, and file modes. int float str bool list tuple dict set frozenset bytes bytearray complex abs round pow divmod sum min max len isalnum isalpha isdigit isidentifier islower isupper isspace endswith startswith find rfind count capitalize lower upper title swapcase replace lstrip rstrip strip format center ljust rjust def parameter argument return recursion local global open read readline readlines write append writelines.

Built-in function signatures from the course plan

String entries are methods called on a string; the other entries are built-in functions.

Type conversion

int(x)

Convert to integer; decimal part truncates.

float(x)

Convert to floating-point number.

str(x)

Convert to string representation.

bool(x)

Convert using Python truth-value rules.

list(iterable)

Build a list from an iterable.

tuple(iterable)

Build an immutable tuple.

dict(...)

Build key-value mapping.

set(iterable)

Build a mutable set of unique values.

frozenset(iterable)

Build an immutable set.

bytes(source)

Build immutable bytes.

bytearray(source)

Build mutable byte sequence.

complex(real, imag=0)

Build a complex number.

Numeric built-ins

abs(x)

Magnitude.

round(x, ndigits=0)

Round to chosen decimal places (ties use round-half-to-even).

pow(x, y[, mod])

Power; optional modular power.

divmod(a, b)

Return quotient and remainder tuple.

sum(iterable[, start])

Add numeric values.

min(iterable)

Smallest item.

max(iterable)

Largest item.

String functions and methods

len(s)

Number of characters.

s.isalnum()

All characters letters/digits; non-empty.

s.isalpha()

All characters alphabetic; non-empty.

s.isdigit()

All characters digits.

s.isidentifier()

Identifier character rules.

s.islower()

Cased letters are lowercase.

s.isupper()

Cased letters are uppercase.

s.isspace()

All characters whitespace.

s.endswith(suffix)

Check suffix.

s.startswith(prefix)

Check prefix.

s.find(sub)

First position, or -1.

s.rfind(sub)

Last position, or -1.

s.count(sub)

Count non-overlapping occurrences.

s.capitalize()

Capitalize first character; lowercase remaining.

s.lower()

Lowercase copy.

s.upper()

Uppercase copy.

s.title()

Title-cased copy.

s.swapcase()

Swap letter cases.

s.replace(old, new)

Replace matching text; returns a copy.

s.lstrip([chars])

Remove leading whitespace or chars.

s.rstrip([chars])

Remove trailing whitespace or chars.

s.strip([chars])

Remove whitespace/chars at both ends.

s.format(...)

Fill replacement fields.

s.center(width[, fill])

Center text to width.

s.ljust(width[, fill])

Left-align text to width.

s.rjust(width[, fill])

Right-align text to width.

User-defined function patterns

def average(values):
    return sum(values) / len(values)

marks = [82, 91, 76]
print(round(average(marks), 1))

def factorial(n):
    if n == 1:       # base case
        return 1
    return n * factorial(n - 1)  # recursive case

Recursion needs a base case and a recursive step that moves toward it.

Virtual-file exam pattern

with open("notes.txt", "w", encoding="utf-8") as file:
    file.write("Practice\n")
with open("notes.txt", "a", encoding="utf-8") as file:
    file.writelines(["Python\n", "Files\n"])
with open("notes.txt", "r", encoding="utf-8") as file:
    print(file.read())

w overwrites, a appends, r reads. write() and writelines() do not add newline characters for you.

Quick self-check: what does find() return when no substring matches?

-1. index() differs: it raises ValueError if the substring is absent.

Unit 5

Modules, packages, Matplotlib, and NumPy

Imports, numeric utilities, charts, arrays, and calculations. import from package math sqrt ceil floor factorial pi gcd matplotlib plot bar hist pie show xlabel ylabel grid savefig numpy array shape ndim size dtype itemsize sum min max mean std var dot cross matmul.

Modules and packages

import math
print(math.sqrt(81))

from math import pi
print(round(pi, 2))

# package.module import pattern
from school_tools.marks import average

A module is a Python file; a package groups related modules. Avoid wildcard imports and filenames that shadow standard modules.

Matplotlib and NumPy quick reference

Matplotlib

plt.plot(x, y), plt.bar(x, y), plt.hist(values), plt.pie(values)

Labels and display

plt.title(...), plt.xlabel(...), plt.ylabel(...), plt.grid(True), plt.show()

Create array

np.array([1, 2, 3])

Inspect

arr.shape, arr.ndim, arr.size, arr.dtype, arr.itemsize

Statistics

np.sum/min/max/mean/std/var(arr)

Linear algebra

np.dot(a,b), np.cross(a,b), np.matmul(a,b)

Quick self-check: what is the shape of a 2-row, 3-column array?

(2, 3). shape describes each dimension; size would be 6 total elements.

A short revision plan

  1. Step 1

    Recall

    Close the notes and write the key rules from memory.

  2. Step 2

    Practise

    Run one example from each unit and change at least one input.

  3. Step 3

    Review

    Use the randomized quiz, then revisit the weakest unit.

This is a revision aid aligned with the provided development plan; consult your official GTU syllabus and instructor's exam instructions for final scope and format.