PCEP-30-02 Certification Exam Syllabus Review

PCEP Certification and Examination Structure

OpenEDG Python Institute PCEP Certification Badge

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 (.pyc files) 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 if condition).

    • 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 like begin/end to 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 IndentationError or TabError.

  • 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: True and False. In numeric evaluations, True evaluates to the integer value 11, and False evaluates to 00.

    • 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., 3.141593.14159). A float can omit leading or trailing zeros (e.g., .5 evaluates to 0.50.5, and 5. evaluates to 5.05.0).

    • Scientific Notation: Expresses numbers multiplied by powers of ten using an e or E symbol. The syntax mEnm\text{E}n or menm\text{e}n equates to m×10nm \times 10^n. For example, 3e4 evaluates to 30000.030000.0, and 1.5e-3 evaluates to 0.00150.0015. Literals using scientific notation are always represented internally as float.

    • Strings (str): Immutable sequences of characters delimited by single ('), double ("), or triple (''' / """) quotes.

  • Numeral Systems:

    • Decimal (Base 10): Standard everyday numbering using digits 00 through 99 without any prefix.

    • Binary (Base 2): Prefixed with 0b or 0B, composed exclusively of digits 00 and 11 (e.g., 0b1011 evaluates to 1×23+0×22+1×21+1×20=111 \times 2^3 + 0 \times 2^2 + 1 \times 2^1 + 1 \times 2^0 = 11 in base 10).

    • Octal (Base 8): Prefixed with 0o or 0O, composed of digits 00 through 77 (e.g., 0o17 evaluates to 1×81+7×80=151 \times 8^1 + 7 \times 8^0 = 15 in base 10).

    • Hexadecimal (Base 16): Prefixed with 0x or 0X, composed of digits 00 through 99 and letters a–f or A–F representing decimal values 1010 through 1515 (e.g., 0x1F evaluates to 1×161+15×160=311 \times 16^1 + 15 \times 16^0 = 31 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, and MY_VARIABLE are 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 7979 characters (and docstrings/comments to 7272 characters).

    • Whitespace: Include single spaces around binary operators (e.g., x=y+2x = y + 2), 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., 2∗∗3=82 ** 3 = 8).

    • *: Multiplication (e.g., 6∗7=426 * 7 = 42).

    • /: Standard float division. Always returns a float object, even when dividing whole numbers evenly (e.g., 4/2=2.04 / 2 = 2.0).

    • //: Floor division (integer division). Divides and rounds down to the nearest integer toward negative infinity (e.g., 7//2=37 // 2 = 3, whereas −7//2=−4-7 // 2 = -4). If either operand is a float, the result is a float rounded to the nearest smaller whole number (e.g., 7.0//2=3.07.0 // 2 = 3.0).

    • %: Modulo (remainder). Computes the remainder of floor division according to the mathematical identity r=x−(x//y)×yr = x - (x // y) \times y (e.g., 77 % 3 = 1; −7-7 % 3 = 2).

    • +: Addition (e.g., 10+5=1510 + 5 = 15).

    • -: Subtraction (e.g., 10−5=510 - 5 = 5).

  • 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" * 3 produces "hahaha"). One operand must be a string and the other an integer; replication with non-integers raises a TypeError.

  • Assignment and Shortcut Operators:

    • Standard assignment: =. Binds an evaluated object reference to a variable name.

    • Augmented assignment operators combine an operation with assignment: +=, -=, *=, /=, //=, %=, **=, &=, |=, ^=, <<=, >>=. The expression x+=5x += 5 is shorthand for x=x+5x = x + 5.

  • 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+yx + y, 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., 10−4−210 - 4 - 2 evaluates as (10−4)−2=4(10 - 4) - 2 = 4).

    • Right-Associative Exception: Exponentiation (**) binds from right to left (e.g., 2∗∗2∗∗32 ** 2 ** 3 evaluates as 2∗∗(2∗∗3)=2∗∗8=2562 ** (2 ** 3) = 2 ** 8 = 256, not (2 ** 2) ** 3 = 64).

    • Order of Precedence (highest to lowest):

    1. Parentheses: () (overrides all default rules)

    2. Exponentiation: **

    3. Unary operators: +, -, ~

    4. Multiplicative operators: *, /, //, %

    5. Additive operators: +, -

    6. Bitwise shift operators: <<, >>

    7. Bitwise AND: &

    8. Bitwise XOR: ^

    9. Bitwise OR: |

    10. Relational / Comparison operators: ==, !=, <, <=, >, >=, is, is not, in, not in

    11. Boolean NOT: not

    12. Boolean AND: and

    13. Boolean OR: or

    14. Assignment and augmented assignment: =, +=, -=, etc.

  • Bitwise Operators:

    • ~ (Bitwise NOT / Inversion): Inverts all bits. For an integer nn, mathematically evaluates as ∼n=−(n+1)\sim n = -(n + 1).

    • & (Bitwise AND): Yields a 1 in each bit position where both corresponding input bits are 1.

    • ^ (Bitwise XOR): Yields a 1 where exactly one of the corresponding input bits is 1.

    • | (Bitwise OR): Yields a 1 where at least one of the corresponding input bits is 1.

    • << (Bitwise Left Shift): Shifts bits left by nn positions, filling trailing positions with zeros. Equivalent to integer multiplication by 2n2^n.

    • >> (Bitwise Right Shift): Shifts bits right by nn positions, discarding displaced bits. Equivalent to floor division by 2n2^n.

  • Boolean Operators and Expressions:

    • not: Unary logical negation. Returns False if operand evaluates to true; returns True if 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 (True or False).

    • Python allows chained comparisons: a<b<ca < b < c is evaluated logically as (a<b) and (b<c)(a < b) \text{ and } (b < c) with operand b evaluated 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 13\frac{1}{3} having an infinite repeating expansion in base 10), rounding errors occur.

    • For example, evaluating 0.1 + 0.2 == 0.3 produces False because 0.1 + 0.2 evaluates internally to 0.300000000000000040.30000000000000004.

  • 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 33; int(-3.9) yields −3-3).

    • float(x): Converts integers or numeric strings to floating-point numbers (e.g., float("3.14") yields 3.143.14).

    • str(x): Returns the string representation of an object.

    • bool(x): Converts an object to True or False based 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= and end=:

    • 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=".") outputs A-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 str data type.

  • Input Conversion with int() and float():

    • Because input() strictly returns string literals, reading numbers requires explicit type casting.

    • Combining int(input("Enter integer: ")) or float(input("Enter float: ")) converts input directly. If the input cannot be parsed as a valid numeric literal, a ValueError is raised.

Section 2: Control Flow – Conditional Blocks and Loops

PCEP-30-02 2.1 – Decision Making and Branching with if

  • Conditional Constructs:

    • Simple if Statement: Evaluates a conditional expression. If the expression evaluates to truthy, the indented suite of instructions executes; otherwise, it is bypassed.

    • if-else Statement: Provides mutual exclusion. If the conditional expression evaluates to truthy, the if block executes; otherwise, execution diverts to the else block.

    • if-elif and if-elif-else Cascades: Evaluates multiple alternative conditions sequentially. Once a condition evaluates to True, its corresponding block executes, and all subsequent elif and else branches are skipped entirely.

  • Multiple vs. Cascaded Conditionals:

    • Multiple consecutive if statements are evaluated independently of one another, allowing multiple non-exclusive blocks to execute if several conditions hold True.

    • Cascaded if-elif-else statements are mutually exclusive; at most one block can execute.

  • Nesting Conditional Statements:

    • An if, elif, or else block 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 pass Instruction:

    • 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, or class), pass satisfies grammatical indentation requirements while executing no operation.

  • Loop Mechanics: while vs. for:

    • while Loop: Conditional loop that repeatedly executes its indented suite as long as a specified test condition evaluates to True. If the condition never turns False and no termination instruction is reached, an infinite loop occurs.

    • for Loop: Collection-controlled iteration that iterates through elements of an iterable sequence (such as a list, string, tuple, or range() 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 from 00 up to, but not including, stop, with a default step of 11.

    • range(start, stop): Generates integers from start up to, but not including, stop, stepping by 11.

    • range(start, stop, step): Generates integers from start to stop - 1, incrementing by step (which can be negative for reverse counting; step cannot be 00, which raises a ValueError).

  • The in Operator in Loops:

    • Acts as iteration glue in for item in sequence:, binding the variable item to each successive element of sequence on each pass.

  • Expanding Loops with while-else and for-else:

    • Python loops can include an optional trailing else branch.

    • The else block executes only if the loop completes its iterations naturally (i.e., when the while condition becomes False, or when the for loop reaches the end of the iterable sequence).

    • If the loop is terminated prematurely using a break statement, the else block is completely skipped.

  • Loop Execution Control: break and continue:

    • 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 (in while) or next element retrieval (in for).

  • Nesting Loops and Conditionals:

    • Loops may contain nested inner loops and conditional blocks.

    • When an inner loop executes a break or continue, 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 constructor list().

  • Indexing and Slicing Operations:

    • Zero-Based Positive Indexing: Elements are indexed from 00 to n−1n - 1, where nn 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; -1 references the last element, -2 the penultimate element, descending to -n for 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 start up to, but not including, index stop, incrementing by step.

    • Default values: start defaults to 0 (or len - 1 if step < 0), stop defaults to len (or end boundary if step < 0), and step defaults to 1.

    • 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 item x to the end of the list, mutating it in place and returning None.

    • list.insert(index, x): Inserts item x at specified position index, shifting subsequent elements to the right. Returns None.

    • list.index(x): Returns the integer index of the first occurrence of item x. If x is absent, raises a ValueError.

    • Additional common list operations include list.pop([i]), list.remove(x), list.reverse(), and list.sort().

  • The del Instruction:

    • 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] * 5 yields [0, 0, 0, 0, 0]) or appending in accumulation loops.

  • Membership Operators: in and not in:

    • Binary relational operators testing whether a specific value exists inside a collection.

    • x in my_list evaluates to True if an element equals x, else False.

    • x not in my_list evaluates to True if x does 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; modifying list_b mutates list_a.

    • Cloning (creating an independent shallow copy) is achieved via slicing: list_b = list_a[:] or list_b = list_a.copy(). In shallow copies, mutating primitive elements in list_b does not affect list_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) or t = 1, 2, 3).

    • Single-element tuple requirement: Must include a trailing comma (e.g., t = (42,) or t = 42,). Writing (42) evaluates simply to an isolated parenthesized integer literal 42.

  • Immutability Characteristics:

    • Once constructed, elements cannot be added, replaced, reordered, or deleted.

    • Attempting item assignment such as t[0] = 99 raises a TypeError.

    • 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 with in / 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 using dict().

    • Access: d[key] returns the associated value. If key does not exist, an indexing operation raises a KeyError.

    • Adding/Updating: d[key] = new_value. If key is absent, the pair is inserted; if key already exists, its previous value is overwritten.

    • Deletion: del d[key] removes the key-value pair from the dictionary, raising a KeyError if the key is not found.

  • Checking Key Existence:

    • Use in and not in to verify key presence without risking a KeyError:

    • 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 a TypeError.

  • Indexing and Slicing Strings:

    • Follows indexing rules identical to lists and tuples.

    • Given s = "Python": s[0] produces "P", s[-1] produces "n", and s[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 object x into 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 -1 if not found), .index(sub) (raises ValueError if 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 def keyword, 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 yield Keyword:

    • A generator function contains at least one yield statement.

    • 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 a yield statement is reached, which produces a value and suspends execution state (local variables and instruction pointer) until the next request.

  • The return Keyword and Result Return Mechanics:

    • The return keyword 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, b returns (a, b)).

  • The None Keyword and Implicit Returns:

    • None is a built-in constant representing the absence of a value (an instance of NoneType).

    • If a function reaches the end of its suite without encountering an explicit return, or executes a bare return statement with no argument, it implicitly returns None.

  • 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):, calling f(10, 20) binds a=10 and b=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 a SyntaxError.

  • 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 →\rightarrow Enclosing →\rightarrow Global →\rightarrow 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 global Keyword: 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 by sys.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 ArithmeticError and LookupError serve 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-except Construct:

    • Blocks of code prone to runtime exceptions are wrapped inside a try block.

    • If an exception occurs within the try block, execution immediately leaves the block and enters the first matching except block.

    • If no exception occurs, the except blocks 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 except Branches:

    • Python checks except clauses 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 except blocks are ignored.

    • Critical Rule: Subclasses (more specific exceptions) must always be placed above their superclasses (more general exceptions). Placing a parent class (such as LookupError or Exception) above a child class (such as IndexError) 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-except block, 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-except block 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 raise keyword 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 O(n2)O(n^2), which makes it less efficient for larger datasets.

[4,,2,7]

bubble srt

[2,4,7]