PCEP-30-02 — Python Institute PCEP - Certified Entry-Level Python Programmer Quick Reference

Compact independent Quick Reference for Python Institute PCEP - Certified Entry-Level Python Programmer (PCEP-30-02): syntax, types, operators, collections, functions, exceptions, and code tracing.

Use this independent Quick Reference 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.

Rapid Scope Map

AreaKnow how to doCommon exam trap
Python basicsRecognize source code, interpreter, syntax, indentation, comments, literals, variablesAssuming indentation is cosmetic; it defines blocks
I/OUse print() and input()input() always returns str
Data typesWork with int, float, bool, str, None, lists, tuples, dictionariesConfusing mutation with reassignment
OperatorsArithmetic, comparison, logical, bitwise, membership, identity** associativity, // with negatives, and/or short-circuiting
Control flowif, elif, else, while, for, range(), break, continue, loop elseLoop else runs only when no break occurs
CollectionsIndex, slice, iterate, mutate lists/dicts, use tuples/stringsSlices tolerate out-of-range indices; direct indexing does not
FunctionsDefine, call, pass arguments, return values, understand scopeMissing return means None
ExceptionsTrace try, except, else, finallyMore specific exceptions must be handled before general ones
ModulesImport modules and namesimport math requires math.sqrt(), but from math import sqrt does not

Python Program Basics

ConceptQuick reference
Source codeHuman-readable .py instructions.
InterpreterExecutes Python code, usually after parsing and compiling it internally to bytecode.
Syntax errorCode cannot be parsed; execution does not start normally.
Runtime exceptionError occurs while executing syntactically valid code.
StatementInstruction such as assignment, if, while, def, import.
ExpressionProduces a value, such as 2 + 3, len(x), x > 0.
VariableName bound to an object; assignment changes a binding.
ObjectRuntime value with type, identity, and value.
CommentStarts with # and continues to end of line.
BlockGroup of indented statements after a header ending with :.

Syntax Essentials

RuleExampleNotes
Indentation defines blocksif x: ...Consistent indentation is required.
Colon starts compound blockif, elif, else, for, while, def, try, exceptHeader line ends with :.
Case-sensitive namestotal and TotalDifferent identifiers.
Assignment binds namesx = 5Creates or rebinds x.
Multiple assignmenta, b = 1, 2Right side is evaluated before binding.
Swapa, b = b, aNo temporary variable needed.
Chained assignmenta = b = 0Both names refer to same object.
Augmented assignmentx += 1Equivalent in effect to update/rebind, with mutability details for containers.
Line continuationParentheses 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()

FeatureExampleResult
Basic outputprint("Hi")Prints Hi and a newline.
Multiple argumentsprint("A", "B")Default separator is one space.
Custom separatorprint("A", "B", sep="-")A-B
Custom endingprint("A", end="!")Ends with ! instead of newline.
print("A", "B", sep="-", end="!")
print("C")
## A-B!C

input()

PatternMeaning
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-inUseTrap
len(x)Length of string/list/tuple/dictNot for numbers.
type(x)Inspect typeExam snippets may rely on exact type.
int(x)Convert to integerint(3.9) truncates toward zero; int("3.9") raises ValueError.
float(x)Convert to floating-pointFloating precision is approximate.
str(x)Convert to stringUseful before concatenation with strings.
bool(x)Truth-value conversionEmpty/zero/None are false-like.
range()Generate integer sequenceStop is excluded.
list(x)Convert iterable to listCreates a new list from iterable elements.
sorted(x)Returns sorted listDoes not mutate original iterable.
sum(x)Sum numeric iterableFails on non-numeric elements.
min(x), max(x)Minimum/maximumEmpty sequence raises ValueError.

Data Types, Literals, and Conversions

TypeLiteral examplesKey behavior
int0, 42, -7, 0b1010, 0o12, 0xAArbitrary-size integer.
float3.14, 2.0, 1e3, -0.5Approximate real number.
boolTrue, FalseBoolean; participates like 1 and 0 in arithmetic.
str"abc", 'abc', """multi"""Immutable sequence of characters.
NoneTypeNoneRepresents absence of value.
list[1, 2, 3]Mutable ordered sequence.
tuple(1, 2), (1,)Immutable ordered sequence.
dict{"a": 1}Mutable key-value mapping.

Truthiness

ValueTruth value
False, NoneFalse
0, 0.0False
"", [], (), {}False
Most other valuesTrue
print(bool(""))     # False
print(bool("0"))    # True
print(bool([]))     # False
print(bool([0]))    # True

String Escapes

EscapeMeaning
\nNewline
\tTab
\\Backslash
\'Single quote
\"Double quote

Operators and Precedence

Operator Groups

CategoryOperatorsNotes
Arithmetic+, -, *, /, //, %, **/ always produces float.
Unary+x, -x, ~x~x is bitwise inversion.
Comparison<, <=, >, >=, ==, !=Result is bool.
Logicalnot, and, orShort-circuit evaluation.
Bitwise integer&, ^, |, ~, <<, >>Operate on integers.
Membershipin, not inWorks with strings, lists, tuples, dict keys.
Identityis, is notObject identity, not value equality.
Assignment=, +=, -=, *=, etc.Assignment is a statement in basic Python usage.

Precedence: High to Low

LevelOperators / constructsExam notes
1Parentheses, indexing, slicing, callsUse parentheses to remove ambiguity.
2**Right-associative.
3Unary +, -, ~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.
10Comparisons, in, isChaining allowed: a < b < c.
11notLower than comparisons.
12andShort-circuits.
13orShort-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 as str + str or list + list.
  • "3" + "4" is "34", not 7.
  • "ha" * 3 is "hahaha".

Logical Operators

ExpressionBehavior
not xBoolean negation.
x and yIf x is false-like, returns x; otherwise returns y.
x or yIf 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

OperatorQuestion answeredExample
==Do values compare equal?[1, 2] == [1, 2] is True.
isAre 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

Control Flow

Conditional Statements

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
else:
    grade = "C"
RuleNotes
if starts condition chainEvaluated first.
elif means “else if”Checked only if previous conditions were false.
else is optionalRuns when no prior condition matched.
Conditions use truthinessAny expression can be tested.

Trap:

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()

FormValues 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

ConstructMeaning
breakExit nearest loop immediately.
continueSkip rest of current iteration; continue with next iteration.
loop elseRuns 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

NeedChooseReason
One of several branchesif / elif / elseConditional selection.
Count-controlled iterationfor i in range(...)Known integer sequence.
Iterate over itemsfor item in collectionDirect traversal.
Repeat until condition changeswhileUnknown iteration count.
Stop search earlybreakAvoid unnecessary iterations.
Skip selected itemcontinueContinue loop without running remaining body.
Detect unsuccessful searchloop elseExecutes only when no break.
Empty placeholder blockpassSyntactically valid no-op.

Collections Quick Reference

Sequence Indexing and Slicing

Applies to strings, lists, and tuples.

OperationMeaning
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.
s = "Python"

print(s[0])        # P
print(s[-1])       # n
print(s[1:5:2])    # yh
print(s[::-1])     # nohtyP

Traps:

  • s[99] raises IndexError.
  • s[2:99] is allowed and stops at the end.
  • Slice stop is excluded.
  • A slice step of 0 raises ValueError.

Strings

Operation / methodExampleNotes
Concatenate"Py" + "thon"Both operands must be strings.
Repeat"ha" * 3Produces "hahaha".
Membership"y" in "Python"Returns True.
Lengthlen("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 / methodEffectReturn value
lst[i]Access elementElement
lst[i] = xReplace elementNone; statement
lst.append(x)Add one item at endNone
lst.extend(xs)Add all items from iterableNone
lst.insert(i, x)Insert before index iNone
lst.remove(x)Remove first matching valueNone; ValueError if absent
lst.pop()Remove and return last itemRemoved item
lst.pop(i)Remove and return item at index iRemoved item
lst.clear()Remove all itemsNone
lst.sort()Sort list in placeNone
lst.reverse()Reverse in placeNone
del lst[i]Delete item at indexStatement
x in lstMembership testbool

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

PatternMeaning
t = (1, 2, 3)Tuple with three elements.
t = 1, 2, 3Tuple 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

OperationExampleNotes
Created = {"a": 1, "b": 2}Key-value pairs.
Accessd["a"]Raises KeyError if key absent.
Safe accessd.get("x")Returns None by default if absent.
Default accessd.get("x", 0)Returns 0 if absent.
Add/replaced["c"] = 3Existing key is overwritten.
Deletedel d["a"]Raises KeyError if key absent.
Membership"a" in dTests keys, not values.
Keysd.keys()View of keys.
Valuesd.values()View of values.
Itemsd.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.

Functions and Scope

Defining and Calling Functions

def area(width, height):
    return width * height

print(area(3, 4))  # 12
ConceptQuick reference
Definitiondef name(parameters): creates a function object.
Callname(arguments) executes the function.
return valueExits function and sends value to caller.
No returnFunction returns None.
return aloneReturns None.
Function bodyDoes not run until function is called.

Parameters and Arguments

PatternExampleNotes
Positionalf(1, 2)Matched by position.
Keywordf(x=1, y=2)Matched by name.
Mixedf(1, y=2)Positional arguments come first.
Default valuedef f(x=0):Used when argument omitted.
Invalid duplicatef(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 behaviorExample / note
Local variableAssigned inside a function by default.
Global variableDefined at module level.
Read globalA function can read a global if not shadowed locally.
Rebind globalRequires global name inside function.
ShadowingLocal 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.

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")
ClauseRuns when
tryCode being protected is attempted.
except SomeErrorMatching exception occurs in try.
elseNo exception occurs in try.
finallyAlways runs after try/except/else path.

Common Exceptions

ExceptionTypical cause
SyntaxErrorInvalid Python syntax; parse-time problem.
IndentationErrorInvalid indentation.
NameErrorName is not defined.
TypeErrorOperation used with incompatible type.
ValueErrorCorrect type, invalid value, such as int("abc").
ZeroDivisionErrorDivision or modulo by zero.
IndexErrorSequence index out of range.
KeyErrorMissing dictionary key.
AttributeErrorObject has no requested attribute/method.
ImportError / ModuleNotFoundErrorImport cannot be completed.

Exception Matching Traps

TrapCorrect habit
General handler firstPut specific exceptions before broader ones.
Assuming else always runselse runs only if try has no exception.
Assuming finally means successfinally runs even after an exception.
Catching wrong exceptionKnow difference between TypeError and ValueError.
try:
    x = int("abc")
except ZeroDivisionError:
    print("zero")
except ValueError:
    print("value")

## value

Modules and Namespaces

Import Forms

FormExampleHow to use imported name
Import moduleimport mathmath.sqrt(9)
Import with aliasimport math as mm.sqrt(9)
Import selected namefrom math import sqrtsqrt(9)
Import selected name with aliasfrom math import sqrt as ss(9)
Import all namesfrom 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))

Trap:

import math
## print(sqrt(16))      # NameError
print(math.sqrt(16))   # Correct

Module Execution Guard

def main():
    print("running directly")

if __name__ == "__main__":
    main()
NameMeaning
__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

  1. Identify types of each variable.
  2. Apply parentheses, indexing, slicing, and function calls first.
  3. Apply operator precedence.
  4. Track assignments and mutations separately.
  5. For loops, write each iteration value.
  6. For break/continue, mark skipped statements.
  7. For functions, create a local scope and track return value.
  8. For exceptions, stop normal flow at the failing statement and jump to matching handler.

Frequent Output Traps

SnippetResult / 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.

Mutate or Return?

OperationMutates original?Returns useful value?
lst.append(x)YesNo, returns None
lst.sort()YesNo, returns None
lst.reverse()YesNo, returns None
sorted(lst)NoYes, new list
s.upper()No, strings immutableYes, new string
s.replace(a, b)No, strings immutableYes, new string
lst[:]NoYes, 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, and bool.
  • Trace if/elif/else chains exactly.
  • Use range(start, stop, step) without including the stop value.
  • Distinguish break, continue, and loop else.
  • 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 module versus from module import name correctly.

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.