PCEP-30-02 Certification Exam Syllabus Review
PCEP Certification and Examination Structure

Section 1: Computer Programming and Python Fundamentals
PCEP-30-02 1.1 – Fundamental Terms and Definitions
Compilation vs. Interpretation Mechanics:
Compilation: The source code written in a high-level programming language is translated in its entirety directly into machine-executable binary machine code by a dedicated program called a compiler before runtime. The resulting binary file can be executed autonomously by the operating system, resulting in faster execution speeds but lower cross-platform portability across distinct hardware architectures.
Interpretation: The source code is read, parsed, validated, and executed line by line in real time by an interpreter program. In standard CPython, source code is first compiled into intermediate bytecode (
.pycfiles) and then executed sequentially on the Python Virtual Machine (PVM). Interpretation allows rapid prototyping and machine independence, but suffers an execution speed penalty compared to compiled machine code. In C language.
Linguistic Architecture of Programming Languages:
Lexis (Lexical Analysis): The vocabulary of the programming language. It defines the set of valid symbols, character sequences, and individual tokens (such as keywords, identifiers, operators, and literals) that are recognized as legitimate atomic units.
Syntax: The formal grammar and structural rules determining how lexical tokens may be combined to form well-formed expressions and statements. A syntax error occurs during the parsing stage when tokens violate grammatical rules (e.g., omitting a colon after an
ifcondition).Semantics: The substantive meaning and logical coherence of syntactically valid constructs. Semantic validity ensures that an instruction produces defined, sensible computer behavior. A program can be syntactically correct but semantically flawed (e.g., dividing an integer by zero, or adding a string to an integer without type casting).
PCEP-30-02 1.2 – Python's Logic and Structure
Keywords (Reserved Words):
Special predefined words reserved by Python's grammar that carry designated structural roles and cannot be used as variable names, function names, or identifiers.
Examples 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.
Instructions and Statements:
An instruction represents a singular directive executed by the Python interpreter. Python statements typically end with a physical newline, although multiple simple statements may be written on a single line separated by a semicolon (
;).
Indentation Rules:
Python uses indentation rather than curly brackets (
{}) or keywords likebegin/endto delimit code blocks (compound statements such as loops, conditionals, and function definitions).Standard convention requires four consecutive spaces per indentation level. Tabs and spaces should never be mixed within the same block, as doing so raises an
IndentationErrororTabError.
Comments:
Python code comments begin with the hash symbol (
#) and extend to the end of the physical line.Comments are ignored by the lexical analyzer and interpreter; they serve purely as human-readable documentation.
Multi-line comment blocks can be simulated using standalone, unassigned triple-quoted strings (
"""..."""or'''...'''), often utilized as formal docstrings for modules, classes, and functions.
PCEP-30-02 1.3 – Literals, Variables, and Numeral Systems
Literal Data Types:
Booleans: Represent truth values with exactly two instances:
TrueandFalse. In numeric evaluations,Trueevaluates to the integer value, andFalseevaluates to.Integers (
int): Whole numbers of arbitrary precision, bounded only by the computer's available memory.Floating-Point Numbers (
float): Numbers that include a fractional part separated by a decimal point (e.g.,). A float can omit leading or trailing zeros (e.g.,.5evaluates to, and5.evaluates to).Scientific Notation: Expresses numbers multiplied by powers of ten using an
eorEsymbol. The syntaxorequates to . For example,3e4evaluates to, and1.5e-3evaluates to. Literals using scientific notation are always represented internally asfloat.Strings (
str): Immutable sequences of characters delimited by single ('), double ("), or triple ('''/""") quotes.
Numeral Systems:
Decimal (Base 10): Standard everyday numbering using digits
throughwithout any prefix.Binary (Base 2): Prefixed with
0bor0B, composed exclusively of digitsand(e.g.,0b1011evaluates to in base 10).Octal (Base 8): Prefixed with
0oor0O, composed of digitsthrough(e.g.,0o17evaluates to in base 10).Hexadecimal (Base 16): Prefixed with
0xor0X, composed of digitsthroughand lettersa–forA–Frepresenting decimal valuesthrough(e.g.,0x1Fevaluates to in base 10).
Variables and Identifier Naming Rules:
Variables are named symbolic memory references pointing to dynamically allocated objects.
An identifier must begin with an uppercase letter, lowercase letter, or an underscore (
_).Subsequent characters can consist of letters, digits (
0–9), or underscores.Identifiers cannot begin with a digit and cannot coincide with any reserved Python keyword.
Python is case-sensitive:
my_variable,My_Variable, andMY_VARIABLEare three distinct identifiers.
PEP-8 Recommendations for Code Style:
Variable and Function Names: Use
snake_case(lowercase words separated by single underscores, e.g.,calculate_tax_rate).Constants: Use uppercase words separated by underscores (e.g.,
MAX_RETRIES,DEFAULT_TIMEOUT).Indentation: Exactly four spaces per indentation level; do not use tabs.
Line Length: Limit physical lines of code to a maximum of
characters (and docstrings/comments tocharacters).Whitespace: Include single spaces around binary operators (e.g.,
), but avoid extraneous spaces immediately inside brackets, parentheses, or preceding commas.
PCEP-30-02 1.4 – Operators and Data Types
Numeric Operators:
**: Exponentiation (power). Raises the left operand to the power of the right operand (e.g.,).*: Multiplication (e.g.,)./: Standard float division. Always returns afloatobject, even when dividing whole numbers evenly (e.g.,).//: Floor division (integer division). Divides and rounds down to the nearest integer toward negative infinity (e.g.,, whereas). If either operand is a float, the result is a float rounded to the nearest smaller whole number (e.g.,).%: Modulo (remainder). Computes the remainder of floor division according to the mathematical identity (e.g.,;).+: Addition (e.g.,).-: Subtraction (e.g.,).
String Operators:
+: Concatenation. Joins two strings end-to-end (e.g.,"py" + "thon"produces"python"). Both operands must be strings.*: Replication. Repeats a string an integer number of times (e.g.,"ha" * 3produces"hahaha"). One operand must be a string and the other an integer; replication with non-integers raises aTypeError.
Assignment and Shortcut Operators:
Standard assignment:
=. Binds an evaluated object reference to a variable name.Augmented assignment operators combine an operation with assignment:
+=,-=,*=,/=,//=,%=,**=,&=,|=,^=,<<=,>>=. The expressionis shorthand for.
Unary vs. Binary Operators:
Unary Operators: Act upon a single operand. Include unary plus (
+x), unary minus (-x), and bitwise inversion (~x).Binary Operators: Act upon two operands positioned on either side of the operator (e.g.,
,x & y).
Operator Priorities and Binding (Precedence and Associativity):
Binding / Associativity: Most binary operators in Python exhibit left-to-right binding (left-associative), evaluating expressions from left to right (e.g.,
evaluates as).Right-Associative Exception: Exponentiation (
**) binds from right to left (e.g.,evaluates as, not(2 ** 2) ** 3 = 64).Order of Precedence (highest to lowest):
Parentheses:
()(overrides all default rules)Exponentiation:
**Unary operators:
+,-,~Multiplicative operators:
*,/,//,%Additive operators:
+,-Bitwise shift operators:
<<,>>Bitwise AND:
&Bitwise XOR:
^Bitwise OR:
|Relational / Comparison operators:
==,!=,<,<=,>,>=,is,is not,in,not inBoolean NOT:
notBoolean AND:
andBoolean OR:
orAssignment and augmented assignment:
=,+=,-=, etc.
Bitwise Operators:
~(Bitwise NOT / Inversion): Inverts all bits. For an integer , mathematically evaluates as .&(Bitwise AND): Yields a1in each bit position where both corresponding input bits are1.^(Bitwise XOR): Yields a1where exactly one of the corresponding input bits is1.|(Bitwise OR): Yields a1where at least one of the corresponding input bits is1.<<(Bitwise Left Shift): Shifts bits left by positions, filling trailing positions with zeros. Equivalent to integer multiplication by .>>(Bitwise Right Shift): Shifts bits right by positions, discarding displaced bits. Equivalent to floor division by .
Boolean Operators and Expressions:
not: Unary logical negation. ReturnsFalseif operand evaluates to true; returnsTrueif false.and: Binary logical conjunction. Evaluates operands using short-circuit evaluation: if the left operand evaluates to falsy, it returns that value immediately without evaluating the right operand. If truthy, it returns the right operand.or: Binary logical disjunction. Short-circuits: if the left operand evaluates to truthy, it returns that value immediately without evaluating the right operand. If falsy, it returns the right operand.Falsy Values in Python:
None,False, numeric zeros (0,0.0,0j), and empty collections/sequences ("",(),[],{},set(),range(0)). All other values are truthy.
Relational (Comparison) Operators:
Operators:
==(equality),!=(inequality),>(greater than),>=(greater than or equal to),<(less than),<=(less than or equal to).All relational operators return a boolean value (
TrueorFalse).Python allows chained comparisons:
is evaluated logically aswith operandbevaluated only once.
Accuracy of Floating-Point Numbers:
Python floats are implemented under the hood as standard IEEE 754 double-precision 64-bit binary floating-point numbers.
Because many decimal fractions cannot be represented exactly in binary base-2 notation (analogous to having an infinite repeating expansion in base 10), rounding errors occur.
For example, evaluating
0.1 + 0.2 == 0.3producesFalsebecause0.1 + 0.2evaluates internally to.
Type Casting (Explicit Type Conversion):
Converting an object explicitly from one data type to another using built-in constructor functions:
int(x): Converts valid string representations of integers or truncates floats toward zero (e.g.,int(3.9)yields;int(-3.9)yields).float(x): Converts integers or numeric strings to floating-point numbers (e.g.,float("3.14")yields).str(x): Returns the string representation of an object.bool(x): Converts an object toTrueorFalsebased on Python truth-value testing rules.
PCEP-30-02 1.5 – Console Input and Output Operations
The
print()Function:Built-in function that formats and prints any number of comma-separated positional arguments to standard output (
sys.stdout).Automatically converts non-string objects to their string representation prior to outputting.
Keyword Parameters
sep=andend=:sep=: Defines the separator string inserted between consecutive positional arguments. Defaults to a single space character:sep=" ".end=: Defines the string appended at the very end of the output. Defaults to a physical newline character:end=" ".Passing custom values alters output formatting (e.g.,
print("A", "B", sep="-", end=".")outputsA-B.without a trailing newline).
The
input()Function:Built-in function designed to capture user text from standard input (
sys.stdin).Accepts an optional prompt string printed to the console without an automatic trailing newline.
Suspends program execution until the user presses Enter, reading user input up to the newline and returning the collected data strictly as a
strdata type.
Input Conversion with
int()andfloat():Because
input()strictly returns string literals, reading numbers requires explicit type casting.Combining
int(input("Enter integer: "))orfloat(input("Enter float: "))converts input directly. If the input cannot be parsed as a valid numeric literal, aValueErroris raised.
Section 2: Control Flow – Conditional Blocks and Loops
PCEP-30-02 2.1 – Decision Making and Branching with if
Conditional Constructs:
Simple
ifStatement: Evaluates a conditional expression. If the expression evaluates to truthy, the indented suite of instructions executes; otherwise, it is bypassed.if-elseStatement: Provides mutual exclusion. If the conditional expression evaluates to truthy, theifblock executes; otherwise, execution diverts to theelseblock.if-elifandif-elif-elseCascades: Evaluates multiple alternative conditions sequentially. Once a condition evaluates toTrue, its corresponding block executes, and all subsequentelifandelsebranches are skipped entirely.
Multiple vs. Cascaded Conditionals:
Multiple consecutive
ifstatements are evaluated independently of one another, allowing multiple non-exclusive blocks to execute if several conditions holdTrue.Cascaded
if-elif-elsestatements are mutually exclusive; at most one block can execute.
Nesting Conditional Statements:
An
if,elif, orelseblock may enclose one or more inner conditional statements.Inner blocks must be indented further to define their hierarchical dependency on outer conditional outcomes.
PCEP-30-02 2.2 – Iteration and Loop Constructs
The
passInstruction:Acts as a syntactical placeholder that performs a null operation.
Because Python syntax forbids empty code suites after statements that require a body (such as
if,for,while,def, orclass),passsatisfies grammatical indentation requirements while executing no operation.
Loop Mechanics:
whilevs.for:whileLoop: Conditional loop that repeatedly executes its indented suite as long as a specified test condition evaluates toTrue. If the condition never turnsFalseand no termination instruction is reached, an infinite loop occurs.forLoop: Collection-controlled iteration that iterates through elements of an iterable sequence (such as a list, string, tuple, orrange()generator) step by step.
The
range()Function:Built-in sequence generator that produces an immutable arithmetic sequence of integers on demand without generating all values in memory upfront.
Signatures:
range(stop): Generates integers starting fromup to, but not including,stop, with a default step of.range(start, stop): Generates integers fromstartup to, but not including,stop, stepping by.range(start, stop, step): Generates integers fromstarttostop - 1, incrementing bystep(which can be negative for reverse counting;stepcannot be, which raises aValueError).
The
inOperator in Loops:Acts as iteration glue in
for item in sequence:, binding the variableitemto each successive element ofsequenceon each pass.
Expanding Loops with
while-elseandfor-else:Python loops can include an optional trailing
elsebranch.The
elseblock executes only if the loop completes its iterations naturally (i.e., when thewhilecondition becomesFalse, or when theforloop reaches the end of the iterable sequence).If the loop is terminated prematurely using a
breakstatement, theelseblock is completely skipped.
Loop Execution Control:
breakandcontinue:break: Immediately and unconditionally aborts the innermost enclosing loop, jumping execution to the first statement following the loop suite.continue: Immediately ends the current iteration of the innermost enclosing loop, skipping remaining statements in the loop body and jumping directly to the loop condition test (inwhile) or next element retrieval (infor).
Nesting Loops and Conditionals:
Loops may contain nested inner loops and conditional blocks.
When an inner loop executes a
breakorcontinue, it alters execution flow only for that specific innermost loop; outer enclosing loops continue executing unaffected.
Section 3: Data Collections – Tuples, Dictionaries, Lists, and Strings
PCEP-30-02 3.1 – Lists: Mechanics and Manipulation
Vector Construction and List Structure:
A list is a mutable, ordered sequence of heterogeneous Python objects enclosed in square brackets (
[]).Can be constructed using literal brackets (e.g.,
my_list = [1, 2, 3]) or the built-in constructorlist().
Indexing and Slicing Operations:
Zero-Based Positive Indexing: Elements are indexed from
to, where is the total length of the list (e.g.,my_list[0]references the first element).Negative Indexing: Accesses elements relative to the end of the list;
-1references the last element,-2the penultimate element, descending to-nfor the first element.Indexing out of range raises an
IndexError.Slicing Syntax:
my_list[start:stop:step]Extracts a new shallow copy of elements starting at index
startup to, but not including, indexstop, incrementing bystep.Default values:
startdefaults to0(orlen - 1ifstep < 0),stopdefaults tolen(or end boundary ifstep < 0), andstepdefaults to1.Unlike indexing, slice indices that exceed list boundaries do not raise errors; Python gracefully clamps them to the nearest valid terminal index.
Complete shallow clone syntax:
my_list[:].
List Methods and Functions:
len(list): Built-in function returning the integer count of elements in the collection.sorted(iterable): Built-in function that returns a new list containing all items from the iterable sorted in ascending order, leaving the original list unaltered.list.append(x): Adds itemxto the end of the list, mutating it in place and returningNone.list.insert(index, x): Inserts itemxat specified positionindex, shifting subsequent elements to the right. ReturnsNone.list.index(x): Returns the integer index of the first occurrence of itemx. Ifxis absent, raises aValueError.Additional common list operations include
list.pop([i]),list.remove(x),list.reverse(), andlist.sort().
The
delInstruction:General statement that removes references to objects or deletes individual elements/slices from mutable collections (e.g.,
del my_list[0]deletes the first element;del my_list[1:3]deletes a slice).
Iterating Through Lists and Initialization:
Standard traversal:
for element in my_list:.Traversal with index tracking:
for index, element in enumerate(my_list):.Common list initialization patterns include replication (e.g.,
[0] * 5yields[0, 0, 0, 0, 0]) or appending in accumulation loops.
Membership Operators:
inandnot in:Binary relational operators testing whether a specific value exists inside a collection.
x in my_listevaluates toTrueif an element equalsx, elseFalse.x not in my_listevaluates toTrueifxdoes not match any element in the list.
List Comprehensions:
Concise syntactic mechanism for constructing new lists from existing iterables based on transformational expressions and optional filtering conditions.
General syntax:
[expression for item in iterable if condition].Example:
[x ** 2 for x in range(6) if x % 2 == 0]evaluates to[0, 4, 16].
Copying vs. Cloning Lists (References vs. Slices):
Assigning a list variable to another variable (e.g.,
list_b = list_a) creates an alias pointing to the identical underlying list object in memory; modifyinglist_bmutateslist_a.Cloning (creating an independent shallow copy) is achieved via slicing:
list_b = list_a[:]orlist_b = list_a.copy(). In shallow copies, mutating primitive elements inlist_bdoes not affectlist_a, though nested mutable sub-objects continue to share memory references.
Multi-Dimensional Lists (Matrices and Cubes):
Lists can hold other lists as nested elements.
Two-Dimensional Matrix: A list of lists accessed via double indexing:
matrix[row][column].Three-Dimensional Cube: A list of lists of lists accessed via triple indexing:
cube[depth][row][column].
PCEP-30-02 3.2 – Tuples: Structure and Immutability
Tuple Definition and Construction:
An immutable, ordered sequence of heterogeneous objects.
Defined using parentheses
()or comma-separated values (e.g.,t = (1, 2, 3)ort = 1, 2, 3).Single-element tuple requirement: Must include a trailing comma (e.g.,
t = (42,)ort = 42,). Writing(42)evaluates simply to an isolated parenthesized integer literal42.
Immutability Characteristics:
Once constructed, elements cannot be added, replaced, reordered, or deleted.
Attempting item assignment such as
t[0] = 99raises aTypeError.Tuples support reading operations identical to lists: positive and negative indexing, slicing (
t[start:stop:step]), and traversal via loops.
Tuples vs. Lists Comparison:
Similarities: Both are sequence data types supporting ordered indexing, negative indexing, slicing, iteration, the
len()function, and membership checking within/not in.Differences: Lists are mutable (can grow, shrink, and modify items in place) and cannot serve as dictionary keys; tuples are immutable, have a smaller memory footprint, and can serve as dictionary keys if all their constituent elements are also hashable.
Composite Structures:
Lists Inside Tuples:
t = ([1, 2], [3, 4]). While the tuple's outer structure cannot change (elements cannot be reassigned or deleted), the internal mutable lists themselves can still be mutated in place (e.g.,t[0].append(99)succeeds).Tuples Inside Lists:
l = [(1, 2), (3, 4)]. The outer list can be modified (items added or deleted), while individual inner tuple items remain strictly immutable.
PCEP-30-02 3.3 – Dictionaries: Key-Value Mapping
Dictionary Definition and Architecture:
A mutable, unordered (in Python 3.7+, insertion-ordered) collection of associative key-value pairs enclosed in curly braces
{}.Keys must be unique and immutable (hashable data types such as integers, floats, strings, and tuples containing only hashables). Values can be of any data type, mutable or immutable, and may repeat.
Building, Indexing, and Modifying Keys:
Syntax:
d = {"key1": "val1", "key2": "val2"}or usingdict().Access:
d[key]returns the associated value. Ifkeydoes not exist, an indexing operation raises aKeyError.Adding/Updating:
d[key] = new_value. Ifkeyis absent, the pair is inserted; ifkeyalready exists, its previous value is overwritten.Deletion:
del d[key]removes the key-value pair from the dictionary, raising aKeyErrorif the key is not found.
Checking Key Existence:
Use
inandnot into verify key presence without risking aKeyError:if "target" in my_dict:
Iteration and Core Dictionary Methods:
Direct iteration over a dictionary defaults to traversing its keys:
for k in my_dict:.dict.keys(): Returns an iterable view object displaying all keys.dict.values(): Returns an iterable view object displaying all mapped values.dict.items(): Returns an iterable view object yielding(key, value)2-tuples, often unpacked in loops:for k, v in my_dict.items():.
PCEP-30-02 3.4 – Strings: Character Sequence Operations
String Construction and Immutability:
Strings are immutable sequences of Unicode code points.
Once instantiated, individual characters within a string cannot be modified, assigned, or removed; attempting
s[0] = "X"raises aTypeError.
Indexing and Slicing Strings:
Follows indexing rules identical to lists and tuples.
Given
s = "Python":s[0]produces"P",s[-1]produces"n", ands[1:4]produces"yth".
Escaping with the Backslash (
\) Character:The backslash introduces escape sequences representing non-printable or special characters:
: Linefeed (newline)
\t: Horizontal tab\\: Literal backslash\': Literal single quote\": Literal double quote
Quotes and Apostrophes Inside Strings:
Strings delimited by double quotes can contain unescaped single quotes/apostrophes:
"He said 'hello'".Strings delimited by single quotes can contain unescaped double quotes:
'He said "hello"'.If the enclosing quote character is used inside the string, it must be escaped using a backslash:
'It\'s sunny'.
Multi-Line Strings:
Delimited using three consecutive single quotes (
'''...''') or three consecutive double quotes ("""...""").Preserve all internal whitespace, tabs, and newlines exactly as entered across physical lines.
Basic String Functions and Methods:
len(s): Returns the total number of characters in the string.str(x): Converts objectxinto its string representation.Common built-in string methods (return new strings since strings are immutable):
Case transformation:
.lower(),.upper(),.capitalize(),.title().Trimming:
.strip(),.lstrip(),.rstrip().Searching and matching:
.find(sub)(returns-1if not found),.index(sub)(raisesValueErrorif not found),.startswith(prefix),.endswith(suffix).Joining and splitting:
.split([sep]),sep.join(iterable).
Section 4: Functions and Exceptions
PCEP-30-02 4.1 – Code Decomposition Using Functions
Defining and Invoking Functions:
Functions provide modularity, code reuse, and encapsulation.
Defined using the
defkeyword, followed by an identifier name, parenthesized formal parameter list, a colon, and an indented block:def function_name(param1, param2):Invoked by calling the identifier followed by parentheses enclosing required arguments:
function_name(arg1, arg2).
Generators and the
yieldKeyword:A generator function contains at least one
yieldstatement.When invoked, it does not execute its body to completion; instead, it returns a generator object conforming to the iterator protocol.
Each call to
next()on the generator resumes execution until ayieldstatement is reached, which produces a value and suspends execution state (local variables and instruction pointer) until the next request.
The
returnKeyword and Result Return Mechanics:The
returnkeyword terminates function execution immediately and transfers control back to the caller.Can pass a computed value or object reference back to the invocation site (e.g.,
return x + y).Multiple values separated by commas in a return statement are automatically bundled and returned as a single tuple (e.g.,
return a, breturns(a, b)).
The
NoneKeyword and Implicit Returns:Noneis a built-in constant representing the absence of a value (an instance ofNoneType).If a function reaches the end of its suite without encountering an explicit
return, or executes a barereturnstatement with no argument, it implicitly returnsNone.
Recursion Mechanics:
A programming technique wherein a function invokes itself directly or indirectly to solve smaller instances of the same problem.
Base Case: A terminating condition that stops recursion without making further recursive calls.
Recursive Step: The self-call that moves the state closer to the base case.
Omitting or misconfiguring the base case leads to infinite recursion, exhausting call stack memory and raising a
RecursionError.
PCEP-30-02 4.2 – Interaction Between Functions and Environments
Parameters vs. Arguments:
Parameters: The variable names defined within the function's formal definition header that receive incoming data.
Arguments: The actual values, variables, or expressions passed into the function call during invocation.
Argument Passing Mechanisms:
Positional Arguments: Arguments matched to parameters based strictly on their relative order from left to right (e.g., in
def f(a, b):, callingf(10, 20)bindsa=10andb=20).Keyword Arguments: Arguments passed by explicitly naming the parameter at the call site (e.g.,
f(b=20, a=10)). Order does not matter when using keywords.Mixed Arguments: Combining positional and keyword arguments. Rule: All positional arguments must precede any keyword arguments in the invocation call. Violating this raises a
SyntaxError(e.g.,f(10, b=20)is legal;f(a=10, 20)is illegal).
Default Parameter Values:
Parameters can be assigned default values in the function definition (e.g.,
def f(a, b=10):).If an argument for that parameter is omitted during invocation, the default value is adopted.
Ordering Rule: In a function definition header, any parameter with a default value must appear after all parameters lacking default values. Placing a non-default parameter after a default parameter (e.g.,
def f(a=10, b):) raises aSyntaxError.
Variable Scopes, Name Hiding (Shadowing), and
global:Scope: The lexical region of a program where an identifier is recognized and accessible.
LEGB Rule: Scope resolution priority traverses outward in the order: Local Enclosing Global Built-in.
Name Hiding (Shadowing): If a variable assigned inside a function shares the same name as a variable in the global scope, the local variable shadows the global one within the function body without altering the global variable's value.
The
globalKeyword: Declares that an identifier inside a local function scope refers to the variable in the module-level global namespace, allowing modification of the global variable from within the function (e.g.,global x).
PCEP-30-02 4.3 – Python Built-In Exceptions Hierarchy
Exception Architecture and Object-Oriented Hierarchy:
In Python, all exceptions are class instances inheriting from a root base class.
When an error occurs, an exception object is instantiated and raised. If not handled, it terminates execution and prints a traceback.
Structural Inheritance Tree of Primary Exceptions:
BaseException(Root base class for all built-in exceptions)SystemExit(Raised bysys.exit(); bypasses standard error handlers so program terminates properly)KeyboardInterrupt(Raised when user interrupts execution via Ctrl+C)Exception(Base class for all non-system-exiting, user-code standard exceptions)ArithmeticError(Abstract base class for numeric calculation anomalies)ZeroDivisionError(Division or modulo by zero)OverflowError(Numeric calculation exceeds maximum representable limit for numeric type)FloatingPointError(Floating-point calculation failure)LookupError(Abstract base class for indexing and key lookup failures)IndexError(Sequence subscript out of range)KeyError(Dictionary key not found in mapping)TypeError(Operation applied to an object of inappropriate data type, e.g.,"abc" + 5)ValueError(Operation receives an argument of correct type but inappropriate value, e.g.,int("hello"))
Abstract Exceptions:
Base classes such as
ArithmeticErrorandLookupErrorserve as conceptual groupings (abstract categories) designed to catch multiple distinct related subclass errors under a single polymorphic handler.
PCEP-30-02 4.4 – Basics of Python Exception Handling
The
try-exceptConstruct:Blocks of code prone to runtime exceptions are wrapped inside a
tryblock.If an exception occurs within the
tryblock, execution immediately leaves the block and enters the first matchingexceptblock.If no exception occurs, the
exceptblocks are skipped entirely.Syntax variant:
try-except Exception:captures all standard program errors while allowing system-level interruptions (KeyboardInterrupt,SystemExit) to pass through unhindered.
Ordering the
exceptBranches:Python checks
exceptclauses sequentially from top to bottom.Once a clause matches the raised exception type or any of its parent superclasses, that block executes and all subsequent
exceptblocks are ignored.Critical Rule: Subclasses (more specific exceptions) must always be placed above their superclasses (more general exceptions). Placing a parent class (such as
LookupErrororException) above a child class (such asIndexError) causes the child branch to become unreachable dead code.
Exception Propagation Through Function Boundaries:
If an exception is raised inside a function and is not caught by a local
try-exceptblock, the function terminates abruptly.The exception propagates upward through the call stack to the calling function.
This upward propagation continues across successive function boundaries until an enclosing
try-exceptblock handles it, or until it reaches the global interpreter level, where execution aborts with an unhandled exception traceback.
Delegating Responsibility for Handling Exceptions:
Functions can intentionally choose not to handle particular exceptions, delegating the responsibility to higher-level caller functions that possess adequate contextual information to handle or log the error gracefully.
Exceptions can also be caught locally, inspected or logged, and then explicitly re-raised using a bare
raisekeyword statement to continue bubbling the exception upward.
bubble sort: moving the largest vals closes to position 1 by going through and stepping each and moving larger value to the right
not a 'functional sort' algorithm but a comparison sort mechanism that operates in a worst-case time complexity of , which makes it less efficient for larger datasets.
[4,,2,7]
bubble srt
[2,4,7]