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:
- Key Language Features & Architectural Design:
- • High-Level Abstraction: Manages memory, pointers, and CPU register allocation automatically.
- • Dynamic Typing: Variables are untyped memory references bound to typed objects in RAM at runtime.
- • Automatic Memory Management: Implements dual-layer memory recovery: primary Reference Counting (deallocating objects immediately when reference count drops to zero) combined with a Generational Cyclic Garbage Collector (Generations 0, 1, 2) to detect and resolve circular reference deadlocks.
- • Batteries-Included Standard Library: Provides built-in modules for networking, math, file I/O, regex, and concurrency.
- CPython Execution Pipeline: Python Source Code (`.py`) $\rightarrow$ Lexer & Parser $\rightarrow$ Abstract Syntax Tree (AST) $\rightarrow$ Bytecode Compiler $\rightarrow$ Platform-Independent Bytecode Instructions (`.pyc`) $\rightarrow$ Python Virtual Machine (PVM Evaluation Loop) $\rightarrow$ Native CPU Machine Execution.
- Runtime Environments & Comments: Interactive REPL (Read-Eval-Print Loop) shell vs Script mode execution (IDLE / Terminal execution via `python script.py`). Single-line comments (`#`) and multi-line documentation strings (`"""docstring"""`) attached to function `__doc__` attributes.
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]
# 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:
- CPython Memory Model (`PyObject`): Every variable name is a reference to a `PyObject` structure in heap memory containing an `ob_refcnt` reference count and `ob_type` type pointer.
- Taxonomy of Python Data Types:
- • Primitive Data Types: `int` (arbitrary precision integer), `float` (IEEE 754 64-bit double precision), `complex` (real + imaginary `a + bj`), `bool` (`True`/`False` subclassed from `int`), `str` (immutable Unicode string).
- • Sequence Collections: `list` (mutable ordered dynamic array), `tuple` (immutable ordered array), `str`.
- • Mapping Types: `dict` (mutable key-value hash table mapping).
- • Set Types: `set` (mutable unordered collection of unique hashable elements).
- Input/Output Stream Handling: `input(prompt)` reads input from standard input (`sys.stdin`) as a `str` (requiring explicit type casting like `int()` or `float()`); `print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)` streams objects to standard output.
- Command Line Arguments (`sys.argv`): List of command-line arguments passed upon script invocation. `sys.argv[0]` contains the executing script's relative or absolute path; `sys.argv[1:]` holds user-supplied arguments.
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:
- Complete Operator Taxonomy:
- • Arithmetic: `+`, `-`, `*`, `/` (float division), `//` (floor division integer truncation), `%` (modulus remainder), `**` (exponentiation).
- • Relational: `==` (value equality), `!=`, `>`, `<`, `>=`, `<=`.
- • Logical Boolean: `and`, `or`, `not` (Enforces short-circuit evaluation: `A and B` skips B if A is False; `A or B` skips B if A is True).
- • Bitwise Two's Complement: `&` (AND), `|` (OR), `^` (XOR), `~` (NOT / Invert bits `-x-1`), `<<` (left bitwise shift), `>>` (right bitwise shift).
- • Identity & Membership: `is`, `is not` (compares object memory address `id(a) == id(b)`) vs `in`, `not in` (checks container membership).
- Precedence & Associativity Hierarchy: Parentheses `()` $\rightarrow$ Exponentiation `**` (Right-to-Left) $\rightarrow$ Unary `+`, `-`, `~` (Right-to-Left) $\rightarrow$ Multiplication/Division `*`, `/`, `//`, `%` $\rightarrow$ Addition/Subtraction `+`, `-` $\rightarrow$ Bitwise Shifts `<<`, `>>` $\rightarrow$ Bitwise AND/XOR/OR $\rightarrow$ Relational/Identity/Membership $\rightarrow$ Logical `not`, `and`, `or`.
| 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
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`.
- **`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.