int · float · complexNumeric values
Syllabus-wide Python revision reference and self-checks
Exam Prep · Units 1–5
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.
Names, values, types, conversion, and readable output. identifier keyword input print int float str bool list tuple set dict literal constant.
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 · complexNumeric values
strImmutable text in quotes
listOrdered and mutable; [ ]
tupleOrdered and immutable; ( )
setUnique hashable elements; { }
dictKey-value pairs; {key: value}
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.
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.
Operator rules, decisions, repetition, and loop control. precedence arithmetic comparison logical bitwise membership identity if elif else while for range break continue pass return.
| Order | Operators | Example |
|---|---|---|
| 1 | Parentheses and grouping | (a + b) * c |
| 2 | Exponentiation | a ** b (right-associative) |
| 3 | Unary +, - | -x |
| 4 | *, /, //, % | a // b |
| 5 | + and - | a + b |
| 6 | Shifts: <<, >> | n << 1 |
| 7 | Bitwise: &, ^, | | mask & flag |
| 8 | Comparisons, in, is | a <= b, x in values |
| 9 | not | not ready |
| 10 | and | valid and active |
| 11 | or | guest or member |
Exponentiation binds more tightly than unary minus: -2 ** 2 is -(2 ** 2), or -4. Parentheses make intent explicit.
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 += 1breakExit the nearest loop.
continueSkip to the next iteration.
passDo nothing; placeholder statement.
returnExit a function and optionally send back a value.
[1, 3, 5]. The stop value 6 is excluded, and the step is 2.
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.
| Type | Syntax | Ordered? | Mutable? | Duplicates? | Typical use |
|---|---|---|---|---|---|
list | [a, b] | Yes | Yes | Yes | Sequence that changes |
tuple | (a, b) | Yes | No | Yes | Fixed record |
set | {a, b} | No positional order | Yes | No | Uniqueness / membership |
dict | {key: value} | Insertion order | Yes | Keys: no | Lookup by key |
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"))It checks whether 'name' is a key. Use values() to check values.
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.
String entries are methods called on a string; the other entries are built-in functions.
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.
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.
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.
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 caseRecursion needs a base case and a recursive step that moves toward it.
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.
-1. index() differs: it raises ValueError if the substring is absent.
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.
import math
print(math.sqrt(81))
from math import pi
print(round(pi, 2))
# package.module import pattern
from school_tools.marks import averageA module is a Python file; a package groups related modules. Avoid wildcard imports and filenames that shadow standard modules.
plt.plot(x, y), plt.bar(x, y), plt.hist(values), plt.pie(values)
plt.title(...), plt.xlabel(...), plt.ylabel(...), plt.grid(True), plt.show()
np.array([1, 2, 3])
arr.shape, arr.ndim, arr.size, arr.dtype, arr.itemsize
np.sum/min/max/mean/std/var(arr)
np.dot(a,b), np.cross(a,b), np.matmul(a,b)
(2, 3). shape describes each dimension; size would be 6 total elements.
Close the notes and write the key rules from memory.
Run one example from each unit and change at least one input.
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.