PCEP-30-02 — Python Institute PCEP - Certified Entry-Level Python Programmer Cheat Sheet
Compact independent Cheat sheet for Python Institute PCEP - Certified Entry-Level Python Programmer (PCEP-30-02): syntax, types, operators, collections, functions, exceptions, and code tracing.
Use this independent Cheat Sheet for the Python Institute PCEP - Certified Entry-Level Python Programmer (PCEP-30-02) to refresh Python fundamentals and trace short code snippets quickly. Focus on exact output, exact exception behavior, type conversions, mutability, and control-flow paths.
Use the tables for a quick pre-exam check. Expand a topic’s notes for explanations, examples, and additional distinctions.
Rapid Scope Map
| Area | Know how to do | Common exam trap |
|---|---|---|
| Python basics | Recognize source code, interpreter, syntax, indentation, comments, literals, variables | Assuming indentation is cosmetic; it defines blocks |
| I/O | Use print() and input() | input() always returns str |
| Data types | Work with int, float, bool, str, None, lists, tuples, dictionaries | Confusing mutation with reassignment |
| Operators | Arithmetic, comparison, logical, bitwise, membership, identity | ** associativity, // with negatives, and/or short-circuiting |
| Control flow | if, elif, else, while, for, range(), break, continue, loop else | Loop else runs only when no break occurs |
| Collections | Index, slice, iterate, mutate lists/dicts, use tuples/strings | Slices tolerate out-of-range indices; direct indexing does not |
| Functions | Define, call, pass arguments, return values, understand scope | Missing return means None |
| Exceptions | Trace try, except, else, finally | More specific exceptions must be handled before general ones |
| Modules | Import modules and names | import math requires math.sqrt(), but from math import sqrt does not |
Python Program Basics
| Concept | Quick reference |
|---|---|
| Source code | Human-readable .py instructions. |
| Interpreter | Executes Python code, usually after parsing and compiling it internally to bytecode. |
| Syntax error | Code cannot be parsed; execution does not start normally. |
| Runtime exception | Error occurs while executing syntactically valid code. |
| Statement | Instruction such as assignment, if, while, def, import. |
| Expression | Produces a value, such as 2 + 3, len(x), x > 0. |
| Variable | Name bound to an object; assignment changes a binding. |
| Object | Runtime value with type, identity, and value. |
| Comment | Starts with # and continues to end of line. |
| Block | Group of indented statements after a header ending with :. |
Notes and examples
Syntax Essentials
| Rule | Example | Notes |
|---|---|---|
| Indentation defines blocks | if x: ... | Consistent indentation is required. |
| Colon starts compound block | if, elif, else, for, while, def, try, except | Header line ends with :. |
| Case-sensitive names | total and Total | Different identifiers. |
| Assignment binds names | x = 5 | Creates or rebinds x. |
| Multiple assignment | a, b = 1, 2 | Right side is evaluated before binding. |
| Swap | a, b = b, a | No temporary variable needed. |
| Chained assignment | a = b = 0 | Both names refer to same object. |
| Augmented assignment | x += 1 | Equivalent in effect to update/rebind, with mutability details for containers. |
| Line continuation | Parentheses or \ | Prefer parentheses for readable continuation. |
Identifiers and Keywords
Valid identifiers:
- May contain letters, digits, and underscores.
- Cannot start with a digit.
- Cannot be a reserved keyword.
- Are case-sensitive.
Core Python 3 reserved words include:
False None True and as assert async await break class continue def del elif else
except finally for from global if import in is lambda nonlocal not or pass raise
return try while with yield
Input, Output, and Basic Built-ins
print()
| Feature | Example | Result |
|---|---|---|
| Basic output | print("Hi") | Prints Hi and a newline. |
| Multiple arguments | print("A", "B") | Default separator is one space. |
| Custom separator | print("A", "B", sep="-") | A-B |
| Custom ending | print("A", end="!") | Ends with ! instead of newline. |
Notes and examples
print("A", "B", sep="-", end="!")
print("C")
## A-B!C
input()
| Pattern | Meaning |
|---|---|
name = input() | Reads a line as str. |
age = int(input()) | Reads text, converts to int. |
x = float(input("x: ")) | Prompt is printed; result is still text until converted. |
Trap:
x = input()
print(x + 1) # TypeError if x is str
print(int(x) + 1) # Correct if x contains an integer literal
High-Use Built-ins
| Built-in | Use | Trap |
|---|---|---|
len(x) | Length of string/list/tuple/dict | Not for numbers. |
type(x) | Inspect type | Exam snippets may rely on exact type. |
int(x) | Convert to integer | int(3.9) truncates toward zero; int("3.9") raises ValueError. |
float(x) | Convert to floating-point | Floating precision is approximate. |
str(x) | Convert to string | Useful before concatenation with strings. |
bool(x) | Truth-value conversion | Empty/zero/None are false-like. |
range() | Generate integer sequence | Stop is excluded. |
list(x) | Convert iterable to list | Creates a new list from iterable elements. |
sorted(x) | Returns sorted list | Does not mutate original iterable. |
sum(x) | Sum numeric iterable | Fails on non-numeric elements. |
min(x), max(x) | Minimum/maximum | Empty sequence raises ValueError. |
print()
print() displays values. It does not return the displayed value; its return value is None.
High-yield options:
print(a, b)separates values with a space by default.sep=changes the separator.end=changes what is printed after the output, defaulting to a newline.
Common examples:
print("A", "B")displaysA B.print("A", "B", sep="-")displaysA-B.print("A", end="")does not move to a new line afterA.
input()
input() reads text and returns a string.
| Goal | Correct pattern |
|---|---|
| Read text | name = input() |
| Read integer | n = int(input()) |
| Read float | x = float(input()) |
| Compare numeric input | Convert first, then compare |
Common mistake: input() does not automatically parse numbers.
Data Types, Literals, and Conversions
| Type | Literal examples | Key behavior |
|---|---|---|
int | 0, 42, -7, 0b1010, 0o12, 0xA | Arbitrary-size integer. |
float | 3.14, 2.0, 1e3, -0.5 | Approximate real number. |
bool | True, False | Boolean; participates like 1 and 0 in arithmetic. |
str | "abc", 'abc', """multi""" | Immutable sequence of characters. |
NoneType | None | Represents absence of value. |
list | [1, 2, 3] | Mutable ordered sequence. |
tuple | (1, 2), (1,) | Immutable ordered sequence. |
dict | {"a": 1} | Mutable key-value mapping. |
Notes and examples
Truthiness
| Value | Truth value |
|---|---|
False, None | False |
0, 0.0 | False |
"", [], (), {} | False |
| Most other values | True |
print(bool("")) # False
print(bool("0")) # True
print(bool([])) # False
print(bool([0])) # True
String Escapes
| Escape | Meaning |
|---|---|
\n | Newline |
\t | Tab |
\\ | Backslash |
\' | Single quote |
\" | Double quote |
Operators and Precedence
Operator Groups
| Category | Operators | Notes |
|---|---|---|
| Arithmetic | +, -, *, /, //, %, ** | / always produces float. |
| Unary | +x, -x, ~x | ~x is bitwise inversion. |
| Comparison | <, <=, >, >=, ==, != | Result is bool. |
| Logical | not, and, or | Short-circuit evaluation. |
| Bitwise integer | &, ^, |, ~, <<, >> | Operate on integers. |
| Membership | in, not in | Works with strings, lists, tuples, dict keys. |
| Identity | is, is not | Object identity, not value equality. |
| Assignment | =, +=, -=, *=, etc. | Assignment is a statement in basic Python usage. |
Notes and examples
Precedence: High to Low
| Level | Operators / constructs | Exam notes |
|---|---|---|
| 1 | Parentheses, indexing, slicing, calls | Use parentheses to remove ambiguity. |
| 2 | ** | Right-associative. |
| 3 | Unary +, -, ~ | Watch -2 ** 2. |
| 4 | *, /, //, % | Same level, left-to-right. |
| 5 | +, - | Addition/subtraction or sequence concat. |
| 6 | <<, >> | Bit shifts. |
| 7 | & | Bitwise AND. |
| 8 | ^ | Bitwise XOR. |
| 9 | | | Bitwise OR. |
| 10 | Comparisons, in, is | Chaining allowed: a < b < c. |
| 11 | not | Lower than comparisons. |
| 12 | and | Short-circuits. |
| 13 | or | Short-circuits. |
Arithmetic Traps
print(2 ** 3 ** 2) # 512, because 2 ** (3 ** 2)
print(-2 ** 2) # -4, because -(2 ** 2)
print((-2) ** 2) # 4
print(7 / 2) # 3.5
print(7 // 2) # 3
print(7 % 2) # 1
print(-7 // 3) # -3, floor division
print(-7 % 3) # 2
Remember:
//is floor division, not simple truncation for negative values.%is the remainder consistent with floor division.+concatenates sequences only when types are compatible, such asstr + strorlist + list."3" + "4"is"34", not7."ha" * 3is"hahaha".
Logical Operators
| Expression | Behavior |
|---|---|
not x | Boolean negation. |
x and y | If x is false-like, returns x; otherwise returns y. |
x or y | If x is true-like, returns x; otherwise returns y. |
print(0 and 5) # 0
print(3 and 5) # 5
print("" or "x") # x
print("a" or "x") # a
Equality vs Identity
| Operator | Question answered | Example |
|---|---|---|
== | Do values compare equal? | [1, 2] == [1, 2] is True. |
is | Are both names bound to the same object? | Use for None: x is None. |
a = [1, 2]
b = [1, 2]
c = a
print(a == b) # True
print(a is b) # False
print(a is c) # True
Arithmetic operators
| Operator | Meaning | Example result |
|---|---|---|
+ | Addition or string/list concatenation | 2 + 3 gives 5; "a" + "b" gives "ab" |
- | Subtraction | 5 - 2 gives 3 |
* | Multiplication or repetition | 3 * 4 gives 12; "ha" * 3 gives "hahaha" |
/ | True division | 5 / 2 gives 2.5 |
// | Floor division | 5 // 2 gives 2; -5 // 2 gives -3 |
% | Modulo | 5 % 2 gives 1 |
** | Exponentiation | 2 ** 3 gives 8 |
Operator precedence to remember
| Higher priority first | Notes |
|---|---|
| Parentheses | Always evaluate first |
** | Exponentiation has high precedence |
Unary +, - | Watch -2 ** 2; exponentiation binds before unary minus |
*, /, //, % | Same level, left to right |
+, - | Same level, left to right |
| Comparisons | <, <=, >, >=, ==, != |
not | Boolean negation |
and | Boolean conjunction |
or | Boolean disjunction |
Common traps:
2 + 3 * 4is14, not20.(2 + 3) * 4is20.5 / 2is2.5, not2.5 // 2is2.-5 // 2floors downward to-3, not toward zero.2 ** 3 ** 2is evaluated right-associatively:2 ** (3 ** 2).
Control Flow
Conditional Statements
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"
Notes and examples
| Rule | Notes |
|---|---|
if starts condition chain | Evaluated first. |
elif means “else if” | Checked only if previous conditions were false. |
else is optional | Runs when no prior condition matched. |
| Conditions use truthiness | Any expression can be tested. |
x = 5
if x > 0:
print("positive")
if x > 3:
print("large")
else:
print("small")
## positive
## large
The else belongs only to the second if.
while Loops
n = 3
while n > 0:
print(n)
n -= 1
Use while when the number of iterations depends on a condition, sentinel value, or state change.
for Loops and range()
| Form | Values produced |
|---|---|
range(5) | 0, 1, 2, 3, 4 |
range(2, 6) | 2, 3, 4, 5 |
range(2, 10, 3) | 2, 5, 8 |
range(5, 0, -2) | 5, 3, 1 |
Rules:
- Start is included.
- Stop is excluded.
- Step cannot be zero.
- Negative step counts down.
for i in range(3):
print(i)
## 0
## 1
## 2
break, continue, and Loop else
| Construct | Meaning |
|---|---|
break | Exit nearest loop immediately. |
continue | Skip rest of current iteration; continue with next iteration. |
loop else | Runs when loop finishes normally, not when exited by break. |
for x in [1, 2, 3]:
if x == 4:
print("found")
break
else:
print("not found")
## not found
i = 0
while i < 5:
i += 1
if i == 3:
continue
print(i)
## 1
## 2
## 4
## 5
Choosing a Control Structure
| Need | Choose | Reason |
|---|---|---|
| One of several branches | if / elif / else | Conditional selection. |
| Count-controlled iteration | for i in range(...) | Known integer sequence. |
| Iterate over items | for item in collection | Direct traversal. |
| Repeat until condition changes | while | Unknown iteration count. |
| Stop search early | break | Avoid unnecessary iterations. |
| Skip selected item | continue | Continue loop without running remaining body. |
| Detect unsuccessful search | loop else | Executes only when no break. |
| Empty placeholder block | pass | Syntactically valid no-op. |
while loops
A while loop repeats while its condition is true.
Review points:
- If the condition is false initially, the body does not run.
- A loop variable must usually be updated inside the loop.
- A missing update can create an infinite loop.
breakexits the nearest loop.continueskips to the next iteration check.
Common trace method:
- Write the initial variable values.
- Check the loop condition.
- Execute the body line by line.
- Record updates.
- Repeat until the condition fails or
breakruns.
for loops
A for loop iterates over an iterable such as a string, list, tuple, dictionary, or range().
| Pattern | Meaning |
|---|---|
for ch in "abc" | Iterates over characters: a, b, c |
for item in [10, 20] | Iterates over list elements |
for i in range(3) | Produces 0, 1, 2 |
for i in range(2, 5) | Produces 2, 3, 4 |
for i in range(1, 6, 2) | Produces 1, 3, 5 |
range() traps
| Expression | Values |
|---|---|
range(5) | 0, 1, 2, 3, 4 |
range(1, 5) | 1, 2, 3, 4 |
range(5, 1, -1) | 5, 4, 3, 2 |
range(1, 5, -1) | No values |
range(1, 5, 0) | Error: zero step is invalid |
The stop value is excluded.
Loop else
Python loops can have an else block. It runs if the loop finishes normally. It does not run if the loop exits with break.
| Situation | Loop else runs? |
|---|---|
| Loop condition becomes false naturally | Yes |
for loop exhausts iterable | Yes |
break executes | No |
continue executes but loop later finishes normally | Yes |
This is a frequent candidate mistake because loop else is not the same as if / else.
Collections Cheat Sheet
Sequence Indexing and Slicing
Applies to strings, lists, and tuples.
| Operation | Meaning |
|---|---|
seq[i] | Element at index i; raises IndexError if out of range. |
seq[-1] | Last element. |
seq[a:b] | Slice from a inclusive to b exclusive. |
seq[a:b:c] | Slice with step c. |
seq[:] | Shallow copy of full sequence. |
seq[::-1] | Reversed sequence. |
Notes and examples
s = "Python"
print(s[0]) # P
print(s[-1]) # n
print(s[1:5:2]) # yh
print(s[::-1]) # nohtyP
Traps:
s[99]raisesIndexError.s[2:99]is allowed and stops at the end.- Slice stop is excluded.
- A slice step of
0raisesValueError.
Strings
| Operation / method | Example | Notes |
|---|---|---|
| Concatenate | "Py" + "thon" | Both operands must be strings. |
| Repeat | "ha" * 3 | Produces "hahaha". |
| Membership | "y" in "Python" | Returns True. |
| Length | len("abc") | Returns 3. |
| Case conversion | "Ab".lower() | Returns new string. |
| Strip whitespace | " x ".strip() | Returns "x". |
| Replace | "abab".replace("a", "x") | Returns "xbxb". |
| Find | "abc".find("b") | Returns index or -1. |
| Split | "a,b".split(",") | Returns ["a", "b"]. |
| Join | ",".join(["a", "b"]) | Returns "a,b". |
String immutability trap:
s = "cat"
## s[0] = "b" # TypeError
s = "b" + s[1:] # Rebinds s to "bat"
Lists
| Operation / method | Effect | Return value |
|---|---|---|
lst[i] | Access element | Element |
lst[i] = x | Replace element | None; statement |
lst.append(x) | Add one item at end | None |
lst.extend(xs) | Add all items from iterable | None |
lst.insert(i, x) | Insert before index i | None |
lst.remove(x) | Remove first matching value | None; ValueError if absent |
lst.pop() | Remove and return last item | Removed item |
lst.pop(i) | Remove and return item at index i | Removed item |
lst.clear() | Remove all items | None |
lst.sort() | Sort list in place | None |
lst.reverse() | Reverse in place | None |
del lst[i] | Delete item at index | Statement |
x in lst | Membership test | bool |
Mutation trap:
nums = [3, 1, 2]
result = nums.sort()
print(nums) # [1, 2, 3]
print(result) # None
Aliasing trap:
a = [1, 2]
b = a
c = a[:]
b.append(3)
print(a) # [1, 2, 3]
print(c) # [1, 2]
Tuples
| Pattern | Meaning |
|---|---|
t = (1, 2, 3) | Tuple with three elements. |
t = 1, 2, 3 | Tuple packing also works. |
one = (1,) | One-element tuple. |
not_tuple = (1) | Just integer 1. |
a, b = (10, 20) | Tuple unpacking. |
Tuple rules:
- Tuples are immutable.
- You can index, slice, iterate, use
len(),in,.count(), and.index(). - A tuple can contain mutable objects, but the tuple’s element bindings cannot be reassigned.
t = ([1, 2], 3)
t[0].append(4)
print(t) # ([1, 2, 4], 3)
Dictionaries
| Operation | Example | Notes |
|---|---|---|
| Create | d = {"a": 1, "b": 2} | Key-value pairs. |
| Access | d["a"] | Raises KeyError if key absent. |
| Safe access | d.get("x") | Returns None by default if absent. |
| Default access | d.get("x", 0) | Returns 0 if absent. |
| Add/replace | d["c"] = 3 | Existing key is overwritten. |
| Delete | del d["a"] | Raises KeyError if key absent. |
| Membership | "a" in d | Tests keys, not values. |
| Keys | d.keys() | View of keys. |
| Values | d.values() | View of values. |
| Items | d.items() | Key-value pairs. |
Dictionary traps:
d = {"a": 1, "b": 2}
print("a" in d) # True
print(1 in d) # False, values are not tested
print(d.get("x")) # None
## print(d["x"]) # KeyError
Keys must be hashable, so common safe key types include strings, numbers, and tuples of hashable elements. Lists cannot be dictionary keys.
Strings
Strings are immutable sequences.
Indexing and slicing
| Expression | Meaning |
|---|---|
s[0] | First character |
s[-1] | Last character |
s[1:4] | Characters at indexes 1, 2, 3 |
s[:3] | From start through index 2 |
s[3:] | From index 3 to end |
s[::-1] | Reversed copy |
If s = "Python":
| Expression | Result |
|---|---|
s[0] | "P" |
s[-1] | "n" |
s[1:4] | "yth" |
s[:2] | "Py" |
s[2:] | "thon" |
Common traps:
- Indexing outside the string raises an error.
- Slicing outside the string usually does not raise an error; it adjusts to valid boundaries.
- Strings cannot be changed in place:
s[0] = "J"is invalid. s.upper()returns a new string; it does not modifys.
String operators and methods
| Operation | Review point |
|---|---|
+ | Concatenates strings |
* | Repeats strings |
in | Checks substring membership |
len(s) | Returns number of characters |
s.lower() / s.upper() | Return transformed copies |
s.strip() | Returns copy with surrounding whitespace removed |
s.split() | Returns a list of substrings |
"sep".join(list) | Joins strings with separator |
Trap: "10" + "5" gives "105", not 15.
Lists
Lists are mutable ordered collections.
List basics
| Operation | Meaning |
|---|---|
lst[0] | First element |
lst[-1] | Last element |
lst[1:3] | Slice copy of selected elements |
lst.append(x) | Adds x to the end |
lst.insert(i, x) | Inserts x at index i |
lst.pop() | Removes and returns last element |
lst.pop(i) | Removes and returns element at index i |
del lst[i] | Deletes element at index i |
len(lst) | Number of elements |
x in lst | Membership test |
Mutability and aliasing
If two variables refer to the same list, changing through one name affects the other.
| Pattern | Result |
|---|---|
b = a | b and a refer to the same list |
b = a[:] | b is a shallow copy |
b = list(a) | b is a shallow copy |
a.append(5) | Mutates the list in place |
Common trap: methods such as append(), sort(), and reverse() modify the list and return None.
Sorting
| Method/function | Behavior |
|---|---|
lst.sort() | Sorts the list in place; returns None |
sorted(lst) | Returns a new sorted list |
lst.reverse() | Reverses in place; returns None |
reversed(lst) | Produces a reverse iterator |
Candidate mistake: assigning lst = lst.sort() makes lst become None.
Tuples
Tuples are immutable ordered collections.
| Concept | Review point |
|---|---|
| Creation | (1, 2, 3) |
| Single-element tuple | (1,), not (1) |
| Indexing | Same style as lists |
| Immutability | Cannot assign to t[0] |
| Can contain mutable objects | The tuple is immutable, but a contained list may still be mutated |
Common trap: parentheses alone do not make a tuple; the comma matters for a single-element tuple.
Dictionaries
Dictionaries store key-value pairs and are mutable.
| Operation | Meaning |
|---|---|
d[key] | Retrieves value for key; error if missing |
d[key] = value | Adds or updates a key-value pair |
key in d | Checks whether key exists |
d.get(key) | Returns value or None if missing |
d.get(key, default) | Returns value or default if missing |
del d[key] | Deletes key-value pair |
d.keys() | View of keys |
d.values() | View of values |
d.items() | View of key-value pairs |
Common traps:
inchecks keys, not values.- Keys must be hashable; lists cannot be dictionary keys.
- Accessing a missing key with
d[key]raises an error. - Assigning to an existing key overwrites the old value.
Functions and Scope
Defining and Calling Functions
def area(width, height):
return width * height
print(area(3, 4)) # 12
Notes and examples
| Concept | Quick reference |
|---|---|
| Definition | def name(parameters): creates a function object. |
| Call | name(arguments) executes the function. |
return value | Exits function and sends value to caller. |
No return | Function returns None. |
return alone | Returns None. |
| Function body | Does not run until function is called. |
Parameters and Arguments
| Pattern | Example | Notes |
|---|---|---|
| Positional | f(1, 2) | Matched by position. |
| Keyword | f(x=1, y=2) | Matched by name. |
| Mixed | f(1, y=2) | Positional arguments come first. |
| Default value | def f(x=0): | Used when argument omitted. |
| Invalid duplicate | f(1, x=2) | TypeError if x got two values. |
def power(base, exponent=2):
return base ** exponent
print(power(3)) # 9
print(power(3, 3)) # 27
print(power(exponent=3, base=2)) # 8
Scope Rules
| Scope behavior | Example / note |
|---|---|
| Local variable | Assigned inside a function by default. |
| Global variable | Defined at module level. |
| Read global | A function can read a global if not shadowed locally. |
| Rebind global | Requires global name inside function. |
| Shadowing | Local name can hide global name. |
x = 10
def show():
print(x)
show() # 10
Scope trap:
x = 10
def bad():
# print(x) # UnboundLocalError if executed before local assignment
x = 5
print(x)
bad() # 5
print(x) # 10
Global rebinding:
count = 0
def inc():
global count
count += 1
inc()
print(count) # 1
Mutable Argument Side Effects
def add_item(items):
items.append("x")
data = []
add_item(data)
print(data) # ['x']
A function can mutate a mutable object passed to it even without returning that object.
Function definition and call
A function definition creates a callable object. The body runs only when the function is called.
Key rules:
- Parameters are names used inside the function.
- Arguments are values passed during the call.
returnsends a value back to the caller and exits the function.- If no
returnruns, the function returnsNone.
Common mistake: confusing displayed output with returned value.
| Function behavior | Effect |
|---|---|
Uses print(x) | Displays x, returns None unless another return exists |
Uses return x | Gives x back to the caller |
Reaches end without return | Returns None |
Executes return inside a loop | Leaves the entire function, not just the loop |
Parameters and arguments
| Type | Example idea | Review point |
|---|---|---|
| Positional | f(1, 2) | Matched by order |
| Keyword | f(a=1, b=2) | Matched by name |
| Default | def f(x=0): | Used when argument omitted |
| Mixed | f(1, b=2) | Positional arguments generally come before keyword arguments |
Common traps:
- A required parameter without a default must receive an argument.
- Do not place a non-default parameter after a default parameter in a function definition.
- Mutable default arguments can preserve changes between calls; for entry-level review, recognize this as risky behavior.
Scope
| Scope idea | Meaning |
|---|---|
| Local variable | Assigned inside a function; normally visible only there |
| Global variable | Defined at top level |
| Name lookup | Python looks for local names before outer/global names |
| Assignment inside function | Creates or updates a local name unless explicitly declared otherwise |
Candidate mistake: assuming assignment inside a function automatically changes a global variable.
Exceptions
Basic Structure
try:
number = int(input())
result = 10 / number
except ValueError:
print("not an integer")
except ZeroDivisionError:
print("division by zero")
else:
print(result)
finally:
print("done")
Notes and examples
| Clause | Runs when |
|---|---|
try | Code being protected is attempted. |
except SomeError | Matching exception occurs in try. |
else | No exception occurs in try. |
finally | Always runs after try/except/else path. |
Common Exceptions
| Exception | Typical cause |
|---|---|
SyntaxError | Invalid Python syntax; parse-time problem. |
IndentationError | Invalid indentation. |
NameError | Name is not defined. |
TypeError | Operation used with incompatible type. |
ValueError | Correct type, invalid value, such as int("abc"). |
ZeroDivisionError | Division or modulo by zero. |
IndexError | Sequence index out of range. |
KeyError | Missing dictionary key. |
AttributeError | Object has no requested attribute/method. |
ImportError / ModuleNotFoundError | Import cannot be completed. |
Exception Matching Traps
| Trap | Correct habit |
|---|---|
| General handler first | Put specific exceptions before broader ones. |
Assuming else always runs | else runs only if try has no exception. |
Assuming finally means success | finally runs even after an exception. |
| Catching wrong exception | Know difference between TypeError and ValueError. |
try:
x = int("abc")
except ZeroDivisionError:
print("zero")
except ValueError:
print("value")
## value
Basic exception handling
try / except lets code handle runtime errors.
Review points:
- Code in
tryruns first. - If a matching exception occurs, the matching
exceptblock runs. - If no exception occurs,
exceptblocks are skipped. - Code after the whole structure continues unless the exception is unhandled or the program exits.
Common exception types to recognize:
| Exception | Typical cause |
|---|---|
ZeroDivisionError | Division or modulo by zero |
ValueError | Correct type but invalid value, such as int("abc") |
TypeError | Operation on incompatible types, such as "3" + 4 |
IndexError | List/string/tuple index out of range |
KeyError | Missing dictionary key |
NameError | Name used before being defined |
Exception trap patterns
| Pattern | What to watch |
|---|---|
Error before try | It will not be caught by that try |
Error after try / except | It must be handled separately |
Multiple except blocks | First matching handler runs |
Broad except first | More specific later handlers may never run |
else with try | Runs only if no exception occurs |
finally | Runs whether or not an exception occurred |
For the exam, focus on identifying whether an error occurs, where it occurs, and whether the provided handler catches it.
Modules and Namespaces
Import Forms
| Form | Example | How to use imported name |
|---|---|---|
| Import module | import math | math.sqrt(9) |
| Import with alias | import math as m | m.sqrt(9) |
| Import selected name | from math import sqrt | sqrt(9) |
| Import selected name with alias | from math import sqrt as s | s(9) |
| Import all names | from math import * | Names copied into current namespace; avoid in real code. |
import math
print(math.pi)
print(math.sqrt(16))
from math import sqrt
print(sqrt(16))
import math
## print(sqrt(16)) # NameError
print(math.sqrt(16)) # Correct
Module Execution Guard
def main():
print("running directly")
if __name__ == "__main__":
main()
| Name | Meaning |
|---|---|
__name__ | Built-in module variable. |
"__main__" | Value when file is run directly. |
| Imported module | __name__ is the module name, not "__main__". |
High-Yield Code-Tracing Patterns
Evaluate in This Order
- Identify types of each variable.
- Apply parentheses, indexing, slicing, and function calls first.
- Apply operator precedence.
- Track assignments and mutations separately.
- For loops, write each iteration value.
- For
break/continue, mark skipped statements. - For functions, create a local scope and track return value.
- For exceptions, stop normal flow at the failing statement and jump to matching handler.
Frequent Output Traps
| Snippet | Result / issue |
|---|---|
print("2" + "3") | 23 |
print(2 + 3) | 5 |
print("2" + 3) | TypeError |
print(10 / 2) | 5.0 |
print(10 // 2) | 5 |
print(3 * "ab") | ababab |
print("abc"[1]) | b |
print("abc"[-1]) | c |
print([1, 2].append(3)) | None |
print(bool("False")) | True |
print(1 == True) | True |
print(1 is True) | Usually False; identity is not equality. |
Notes and examples
Mutate or Return?
| Operation | Mutates original? | Returns useful value? |
|---|---|---|
lst.append(x) | Yes | No, returns None |
lst.sort() | Yes | No, returns None |
lst.reverse() | Yes | No, returns None |
sorted(lst) | No | Yes, new list |
s.upper() | No, strings immutable | Yes, new string |
s.replace(a, b) | No, strings immutable | Yes, new string |
lst[:] | No | Yes, shallow copy |
Mini Drill Snippets
Trace these until the result is automatic.
x = [1, 2, 3]
y = x
z = x[:]
x.append(4)
y[0] = 9
print(x)
print(z)
## [9, 2, 3, 4]
## [1, 2, 3]
total = 0
for i in range(1, 5):
if i % 2 == 0:
continue
total += i
print(total)
## 4
def f(x):
if x > 0:
return x
return -x
print(f(-3))
print(f(0))
print(f(3))
## 3
## 0
## 3
try:
print("A")
print(1 / 0)
print("B")
except ZeroDivisionError:
print("C")
finally:
print("D")
## A
## C
## D
Final Review Checklist
Before test day, make sure you can:
- Predict output for short Python snippets without running them.
- Explain why
/,//, and%produce different results. - Convert safely between
str,int,float, andbool. - Trace
if/elif/elsechains exactly. - Use
range(start, stop, step)without including the stop value. - Distinguish
break,continue, and loopelse. - Slice strings/lists/tuples using positive and negative indices.
- Identify which list methods mutate and return
None. - Distinguish list aliasing from list copying.
- Recognize tuple singleton syntax:
(x,). - Remember that dictionary membership tests keys.
- Trace function calls, local variables, defaults, and return values.
- Match common exceptions to likely causes.
- Use
import moduleversusfrom module import namecorrectly.
Next step: complete a timed mixed set of original PCEP-30-02 practice questions, then review every missed item by rewriting the code path, variable values, and final output or exception.
Notes and examples
High-yield tracing checklist
When a question asks “What is the output?” or “What is the result?”, use this order:
- Check for syntax or indentation problems. If code cannot parse, execution never starts.
- Record initial assignments. Track variable values carefully.
- Apply type rules. Decide whether operations are numeric, string, list, or invalid.
- Apply precedence. Parentheses first, then operators.
- Trace branches. In an
if/elifchain, only the first true branch runs. - Trace loops one iteration at a time. Update loop variables after each body execution.
- Watch mutation. Lists and dictionaries may change in place.
- Separate
print()fromreturn. Output and return values are not the same. - Check exception location. Determine whether the error is inside a matching
try. - Confirm final output formatting. Spaces, newlines, separators, and
end=matter.
What to review first
For PCEP-30-02, prioritize these areas:
| Area | What to know cold | Typical exam trap |
|---|---|---|
| Program structure | Statements, indentation, comments, basic execution flow | Treating indentation as optional |
| Data types | int, float, str, bool, None | Confusing display form with stored value |
| Operators | Arithmetic, comparison, Boolean, assignment | Precedence and integer division |
| Input/output | print(), input(), type conversion | Forgetting input() returns a string |
| Control flow | if / elif / else, while, for, break, continue, else on loops | Misreading loop termination conditions |
| Collections | Lists, tuples, dictionaries, strings | Mutability, indexing, slicing boundaries |
| Functions | Defining, calling, parameters, return values, scope | Confusing print() with return |
| Exceptions | Basic try / except, common exception types | Catching too broadly or expecting errors at the wrong time |
| Modules and built-ins | Import basics and common built-in functions | Namespace and call syntax mistakes |
Python execution basics
Python executes code mostly from top to bottom. The exam often uses short snippets where one line changes the meaning of the next.
| Concept | Review point |
|---|---|
| Case sensitivity | Name, name, and NAME are different identifiers |
| Indentation | Defines code blocks after if, loops, functions, and exception handlers |
| Comments | # starts a single-line comment |
| Statement order | A variable must be assigned before it is used |
| Dynamic typing | A variable name can later refer to a value of a different type |
| Errors | Some errors occur before execution; others occur only when the line runs |
Common mistake: assuming Python “declares” variable types. In Python, names refer to objects; the object has the type.
Literals, variables, and basic types
Core types
| Type | Example | Key behavior |
|---|---|---|
int | 7, -3, 0 | Whole numbers; unlimited practical precision subject to memory |
float | 3.14, 2.0 | Approximate decimal values |
str | "Python", 'PCEP' | Immutable sequence of characters |
bool | True, False | Subclass-like behavior with numeric contexts, but treat as logical values |
NoneType | None | Represents absence of a value |
Notes and examples
Type conversion traps
| Expression | Result idea | Trap |
|---|---|---|
int("10") | Converts string to integer | Fails if the string is not a valid integer literal |
float("3.5") | Converts string to float | Result is numeric, not text |
str(10) | Converts integer to string | "10" is not the same as 10 |
bool(0) | False | Nonzero numbers are usually True |
bool("") | False | Non-empty strings are usually True, even "False" |
High-yield rule:
input()always returns a string. Convert before numeric comparison or arithmetic.
Example decision:
age = input()gives a string.age + 1is an error unlessageis converted.int(age) + 1performs numeric addition if the input is valid.
Comparisons and Boolean logic
Comparisons
| Operator | Meaning |
|---|---|
== | Equal value |
!= | Not equal value |
<, <= | Less than, less than or equal |
>, >= | Greater than, greater than or equal |
is | Same object identity, not general equality |
in | Membership test |
Notes and examples
For entry-level questions, prefer == for value comparison. Do not use is to compare ordinary numbers or strings unless the question is specifically about identity.
Truthiness
| Value | Boolean interpretation |
|---|---|
0, 0.0 | False |
"" | False |
[], (), {} | False |
None | False |
| Nonzero numbers | True |
| Non-empty strings/collections | True |
Trap: "0" is a non-empty string, so it is True in Boolean context.
Boolean short-circuiting
| Expression | What Python may skip |
|---|---|
A and B | If A is false, B is not evaluated |
A or B | If A is true, B is not evaluated |
This matters when the skipped expression would call a function, modify a variable, or raise an exception.
Conditional logic
if, elif, else
Use if for the first condition, elif for additional alternatives, and else as the fallback.
Key rules:
- Only the first true branch in an
if/elifchain runs. elsehas no condition.- Indentation determines what belongs to the branch.
Common trap:
- Multiple separate
ifstatements can all run. - An
if/elif/elsechain runs at most one branch.
| Structure | Behavior |
|---|---|
if A: ... if B: ... | Both tests are independent |
if A: ... elif B: ... | Test B only if A is false |
if A: ... else: ... | Exactly one branch runs |
Nested conditions
Read nested code by indentation, not by visual closeness. Exam questions may align an else with an inner if, not the outer one.
Decision rule:
- Match each
elseto the nearest precedingifat the same indentation level. - Evaluate outer conditions first.
- Enter only the block whose condition permits it.
Modules and imports
Python code can use modules to organize reusable functionality.
| Import form | How to use it |
|---|---|
import math | Call with math.sqrt(9) |
from math import sqrt | Call with sqrt(9) |
import math as m | Call with m.sqrt(9) |
from math import * | Imports many names directly; can obscure where names came from |
Common traps:
- After
import math,sqrt(9)alone is not available unless imported directly. - After
from math import sqrt,math.sqrt(9)is not available unlessmathwas also imported. - Aliases replace the original module name in that namespace: after
import math as m, usem, not necessarilymath.
Built-in functions to recognize
| Function | Purpose | Trap |
|---|---|---|
len(x) | Length of a sequence or collection | Does not work on plain integers |
type(x) | Returns the type object | Useful for reasoning, not usually for production branching |
int(x) | Converts to integer when valid | Truncates floats toward zero |
float(x) | Converts to float when valid | May produce approximate values |
str(x) | Converts to string | Enables concatenation with other strings |
bool(x) | Converts using truthiness | "False" becomes True |
range() | Produces integer sequence for iteration | Stop value excluded |
sum() | Adds numeric iterable values | Fails on mixed incompatible values |
min() / max() | Finds smallest/largest | Comparisons must be valid |
print() | Displays output | Returns None |
input() | Reads text | Always returns str |
Common candidate mistakes
| Mistake | Correct thinking |
|---|---|
Treating input() as numeric | It returns str; convert explicitly |
| Forgetting indentation defines blocks | Count indentation levels before tracing |
Confusing / and // | / gives float-style true division; // floors |
| Assuming slices include the stop index | Stop index is excluded |
| Assuming list methods return the changed list | Many in-place methods return None |
Using is for ordinary equality | Use == for value comparison |
| Forgetting strings are immutable | String methods return new strings |
| Thinking tuple parentheses always matter | For single-element tuples, the comma matters |
Assuming dictionary in checks values | It checks keys |
Confusing break and continue | break exits loop; continue skips to next iteration |
Missing loop else behavior | Loop else runs only without break |
Assuming print() returns printed text | print() returns None |
| Ignoring short-circuit behavior | Right side may not run |
| Overlooking aliasing | Two names can refer to the same mutable object |
Quick decision tables
“Will this modify the original object?”
| Operation | Modifies original? |
|---|---|
lst.append(x) | Yes |
lst.sort() | Yes |
lst.reverse() | Yes |
lst + [x] | No, creates a new list |
s.upper() | No, strings are immutable |
s.replace(a, b) | No, returns a new string |
d[key] = value | Yes |
t[0] = x | Invalid for tuple |
Notes and examples
“Will this raise an error?”
| Situation | Likely result |
|---|---|
"3" + "4" | "34" |
"3" + 4 | TypeError |
int("4") + 3 | 7 |
int("4.5") | ValueError |
float("4.5") | 4.5 |
[1, 2][5] | IndexError |
[1, 2][1:5] | Valid slice |
{"a": 1}["b"] | KeyError |
{"a": 1}.get("b") | None |
10 / 0 | ZeroDivisionError |
“Which branch runs?”
| Code shape | Result |
|---|---|
if A and A true | if block runs |
if A false, elif B true | elif block runs |
if A false, all elif false | else block runs if present |
Separate if statements | Each condition is tested independently |
Nested if | Inner condition tested only if outer path is entered |
Practice strategy after this review
After reading this page, move directly into original practice questions rather than rereading theory repeatedly. A good IT Mastery question bank should help you:
- Drill one topic at a time, such as operators, loops, lists, functions, or exceptions.
- Practice short code-tracing questions under time pressure.
- Review detailed explanations for both correct and incorrect choices.
- Identify whether mistakes come from syntax, type rules, control flow, or output formatting.
- Revisit weak areas with targeted topic drills before attempting full mock exams.
For Python Institute PCEP - Certified Entry-Level Python Programmer (PCEP-30-02) preparation, the most efficient next step is to complete a small set of topic drills, review every explanation carefully, and then take a mixed mock exam to confirm that you can apply the rules without prompts.