Reference Manual • Chapter 1

Python Fundamentals, Syntax & Operator Precedence

An authoritative reference manual on CPython internals, PVM bytecode execution, garbage collection, variables, primitive/collection data types, input/output, sys.argv, and operator precedence rules.

Python is a high-level, interpreted, dynamically typed, and object-oriented programming language engineered for developer productivity and clean code readability. This chapter provides an exhaustive theoretical analysis of Python execution mechanics, CPython runtime structures, core data types, input/output operations, command-line arguments, and operator evaluation hierarchies.

1.1. 1. Features of Python & CPython Interpreter Execution Model

Definition: Python utilizes a hybrid compilation-interpretation execution model where source code (.py) is lexed, parsed into an Abstract Syntax Tree (AST), compiled into intermediate Bytecode (.pyc), and executed by the Python Virtual Machine (PVM) evaluation loop.

Core Working Principles:

⚙️ Layman Analogy: Musical Sheet vs Live Orchestra Conductor

Compiled Languages (C/C++): Like translating an entire book into a foreign language before publishing—compiles source code directly into native machine instructions prior to execution.

Python Interpreter (CPython): Like a live simultaneous interpreter—compiles source code into intermediate bytecode sheet music (.pyc) and conducts the PVM Virtual Machine engine to execute each instruction live on the CPU!

graph TD
    Source[Python Source Code .py] --> Lexer[Lexer & Parser: Abstract Syntax Tree AST]
    Lexer --> Compiler[Bytecode Compiler]
    Compiler --> Bytecode[Platform-Independent Bytecode .pyc]
    Bytecode --> PVM[Python Virtual Machine PVM Loop]
    PVM --> RefCount[Primary Memory: Reference Counting]
    PVM --> GenGC[Cyclic GC: Gen 0, Gen 1, Gen 2]
    PVM --> CPU[CPU Machine Instruction Execution]
                    
Architecture Specification 1.1: CPython Virtual Machine (PVM) & Garbage Collection Pipeline
# Execution Environment & CPython Internal Inspection
import sys
import gc

def display_execution_info():
    """Docstring: Displays runtime CPython interpreter version, GC stats, and platform target."""
    print("CPython Version:", sys.version)
    print("Target Platform:", sys.platform)
    print("Garbage Collection Thresholds (Gen0, Gen1, Gen2):", gc.get_threshold())
    print("Docstring Inspection:", display_execution_info.__doc__)

if __name__ == "__main__":
    display_execution_info()
5-Marks Exam Scoring Points
  • Python source code (.py) is compiled into intermediate Bytecode (.pyc) before PVM execution.
  • CPython uses Reference Counting for immediate object deallocation and Generational GC for cyclic reference recovery.
  • Docstrings specified with triple quotes (""") populate the internal __doc__ attribute of functions and classes.

1.2. 2. Variables, Data Types, Input/Output & Command Line Arguments

Definition: Variables in Python are untyped memory pointers referencing typed PyObject headers in RAM; the language categorizes types into primitives, sequences, mappings, and sets.

Core Working Principles:

import sys

# Command Line Argument Inspection
print(f"Executing Script: {sys.argv[0]}")
if len(sys.argv) > 1:
    user_name = sys.argv[1]
else:
    user_name = input("Enter User Name: ")

# Explicit Type Casting & Input Parsing
age = int(input("Enter Age (int): "))
gpa = float(input("Enter GPA (float): "))

# Data Structure Category Demonstration
user_mapping = {"name": user_name, "age": age, "gpa": gpa}  # Dict (Mapping)
skills_set = {"Python", "SQL", "Linux", "Python"}         # Set (Deduplicated)

# Advanced Stream Output
print("Profile Mapping:", user_mapping, sep=" => ", end="

")
print(f"Unique Skills Set ({type(skills_set).__name__}): {skills_set}")
5-Marks Exam Scoring Points
  • input() always captures text as a string; explicit type conversion functions (int(), float()) convert inputs.
  • sys.argv[0] holds the script path; sys.argv[1:] receives additional terminal arguments.
  • Dictionaries represent mapping types; Sets enforce unique unordered elements.

1.3. 3. Operators, Bitwise Logic & Precedence Hierarchy

Definition: Operators execute computations on operands; expression evaluation is governed by formal precedence levels and associativity rules.

Core Working Principles:

Precedence Tier Operators Description Associativity Direction
1 (Highest) (), [], {} Parentheses Grouping, Indexing, Brackets Left-to-Right
2 ** Exponentiation Power Right-to-Left ⚠️
3 +x, -x, ~x Unary Signs & Bitwise NOT Right-to-Left
4 *, /, //, % Multiplication, Division, Floor Div, Modulo Left-to-Right
5 +, - Addition & Subtraction Left-to-Right
6 <<, >> Bitwise Left Shift & Right Shift Left-to-Right
7 &, ^, | Bitwise AND, XOR, OR Left-to-Right
8 ==, !=, is, in Relational, Identity & Membership Left-to-Right
9 (Lowest) not, and, or Logical Boolean Short-Circuit Left-to-Right
# Precedence & Associativity Proof Script

# 1. Exponentiation Right-to-Left Associativity Proof
exp_val = 2 ** 3 ** 2  # Evaluates 3**2 = 9, then 2**9 = 512 (NOT (2**3)**2 = 64)
print(f"2 ** 3 ** 2 = {exp_val}")

# 2. Bitwise Logic Demonstration (8-bit binary operations)
a = 12  # Binary: 0000 1100
b = 5   # Binary: 0000 0101
print(f"Bitwise AND (12 & 5): {a & b}")   # 4  (0000 0100)
print(f"Bitwise OR  (12 | 5): {a | b}")   # 13 (0000 1101)
print(f"Left Shift  (12 << 2): {a << 2}") # 48 (0011 0000)

# 3. Identity (is) vs Value Equality (==)
list_a = [1, 2, 3]
list_b = [1, 2, 3]
print(f"list_a == list_b: {list_a == list_b}")  # True (Content matches)
print(f"list_a is list_b: {list_a is list_b}")  # False (Distinct memory addresses: id(list_a) != id(list_b))
5-Marks Exam Scoring Points
  • Exponentiation (**) evaluates Right-to-Left (e.g. 2**3**2 = 512).
  • The is operator tests memory identity (id(a) == id(b)); == tests value equivalence.
  • Logical operators (and, or) utilize short-circuit evaluation for execution speed.

✍️ Chapter 1 Reference Exercises & Review Problems

Exercise 1.1: Trace the step-by-step evaluation order of `result = 15 + 4 * 2 ** 3 // 4 - 5`. State the intermediate value at each precedence step.
Step-by-Step Reference Solution:
1. **Exponentiation (`**`):** `2 ** 3 = 8`. Expression becomes: `15 + 4 * 8 // 4 - 5`.
2. **Multiplication (`*`):** `4 * 8 = 32` (Left-to-Right evaluation for `*` and `//`). Expression becomes: `15 + 32 // 4 - 5`.
3. **Floor Division (`//`):** `32 // 4 = 8`. Expression becomes: `15 + 8 - 5`.
4. **Addition (`+`):** `15 + 8 = 23` (Left-to-Right evaluation for `+` and `-`). Expression becomes: `23 - 5`.
5. **Subtraction (`-`):** `23 - 5 = 18`! Final Result: `18`.
Exercise 1.2: Explain the execution flow of `sys.argv`. What error occurs if a user executes `python script.py` without providing arguments when accessing `sys.argv[1]`?
Step-by-Step Reference Solution:
- **`sys.argv` Mechanics:** `sys.argv` is a Python list containing command-line arguments passed to a script. Index `0` stores the script's path/filename.
- **Error Behavior:** If a user invokes `python script.py` without extra parameters, `len(sys.argv)` equals `1`. Accessing `sys.argv[1]` attempts to read index 1 of a 1-element list, triggering an **`IndexError: list index out of range`**!
- **Prevention:** Always check `if len(sys.argv) > 1:` before indexing, or use `argparse` for robust CLI option parsing.