Ch 01Introduction to Python and the Coding Environment
Chapter 01 of 08·15 min

Introduction to Python and the Coding Environment

Welcome to the Center of Excellence's Python, Data Science & Machine Learning Workshop Series. Python has become the lingua franca of computational science, artificial intelligence, automated reasoning, and backend infrastructure. In this foundational chapter, you will deconstruct how computers execute code, how the Python interpreter transforms human-readable text into machine instructions, and how to write, format, and debug fundamental Python statements.

Learning objectives
  • 01Understand how the Python interpreter executes code sequentially from top to bottom
  • 02Master the print() function with single/multiple arguments, custom separators (sep), and line endings (end)
  • 03Document software effectively using single-line (#), inline, and multi-line docstring comments
  • 04Evaluate mathematical expressions using arithmetic operators (+, -, *, /, //, %, **) adhering to PEMDAS precedence
  • 05Identify, diagnose, and resolve SyntaxError, NameError, TypeError, and ZeroDivisionError tracebacks
  • 06Identify critical edge cases including floating-point representation quirks, division by zero, and string quoting traps

1.1 The Computational Model: Why Python Powers Data Science & AI

Every digital computer operates on a simple cycle: fetch instructions from memory (RAM), decode them in the Central Processing Unit (CPU), execute arithmetic or logic, and store the result. However, writing raw machine code (binary zeros and ones) or low-level assembly is prohibitively slow and error-prone for humans. Python was created by Guido van Rossum in 1991 with an overarching architectural priority: **developer velocity and conceptual readability**. Unlike languages requiring explicit memory management (C/C++) or verbose boilerplate (Java), Python provides a clean syntax resembling mathematical pseudocode. In data science and AI, where researchers iterate rapidly over statistical algorithms, Python's simplicity allows practitioners to focus on mathematical models rather than mechanical memory allocation.
Hands-On Interactive Practice
Every code example on this platform can be run and edited directly in the code editor on your screen. Modifying values, testing variations, and observing the immediate output is the most effective way to build programming intuition.

1.2 How Python Runs Your Code

When you write Python instructions, you are writing **source code** in plain text (typically saved in files ending in `.py`). When you run a Python script, the Python interpreter reads your instructions from top to bottom, translates each statement into actions the computer can execute, and outputs the result immediately. Because Python executes instructions directly without requiring you to run a separate manual compilation step, it is known as an **interpreted language**. This allows you to write code, test it instantly, and fix errors quickly.
Statement 1: The print() Statement — Standard Console Output

Displaying text strings and numeric values on the console.

# Basic output statement
print("Center of Excellence: Data Science & Artificial Intelligence")
print(2026)
print("Workshop 01: Python Foundations")
Execution walkthrough
  1. 1.Line 2: The interpreter parses the string literal "Center of Excellence..." and emits it to stdout with a trailing newline.
  2. 2.Line 3: The integer literal 2026 is converted to its string representation '2026' and output.
  3. 3.Line 4: Emits the third line and flushes the buffer.
Expected output
Center of Excellence: Data Science & Artificial Intelligence
2026
Workshop 01: Python Foundations
Edge cases

• Omitting quotes around text: print(Hello) raises NameError: name 'Hello' is not defined because Python treats unquoted words as variable names. • Capitalizing Print(): Raises NameError: name 'Print' is not defined. Python identifiers are strictly case-sensitive.

Why it happens: By default, print() appends an invisible '\n' (newline character) to the end of every call.

Statement 2: Multi-Argument print() with Custom sep and end

Controlling the delimiter between arguments and the final trailing character.

# Multi-argument print with custom separator
print("Node", "Weight", "Bias", sep=" | ")
print("Alpha", 0.85, 0.12, sep=" -> ")

# Suppressing the default newline with end=""
print("Initializing security scanner", end="... ")
print("READY [OK]")
Execution walkthrough
  1. 1.Line 2: Outputs each string separated by ' | ' instead of spaces.
  2. 2.Line 3: Outputs strings and numbers separated by ' -> '.
  3. 3.Line 6: Sets end='... ', keeping the console cursor on the same line.
  4. 4.Line 7: Appends 'READY [OK]' immediately on the same line.
Expected output
Node | Weight | Bias
Alpha -> 0.85 -> 0.12
Initializing security scanner... READY [OK]
Edge cases

• Passing an integer to sep or end: print('A', 'B', sep=10) raises TypeError: sep must be None or a string, not int. • Setting sep='': Concatenates arguments directly without any spacing: print(1, 2, 3, sep='') yields '123'.

Why it happens: Overriding 'end' allows you to build single-line progress outputs or format continuous data streams.

Statement 3: Multi-Line Strings & Escape Sequences

Working with triple-quoted strings and escaped characters.

# Triple-quoted multi-line string
report = """[SYSTEM REPORT]
Status : Active
Cluster: CoE-Alpha-01"""
print(report)

# Escape sequences: \n (newline), \t (tab), \" (escaped quote)
print("\tSecurity Metric:\t98.5%\n\tVerdict:\t\"CLEAN\"")
Execution walkthrough
  1. 1.Lines 2-4: Assigns a multi-line string containing raw newlines to the variable 'report'.
  2. 2.Line 5: Prints the multi-line string preserving exact visual layout.
  3. 3.Line 8: Interprets '\t' as tab indentation, '\n' as newline, and '\"' as literal quotation marks.
Expected output
[SYSTEM REPORT]
Status : Active
Cluster: CoE-Alpha-01
	Security Metric:	98.5%
	Verdict:	"CLEAN"
Edge cases

• Windows file paths: print('C:\Users\notes.txt') can trigger bugs because '\U' or '\n' is interpreted as an escape sequence. Fix by using raw strings: print(r'C:\Users\notes.txt') or forward slashes: print('C:/Users/notes.txt').

Why it happens: Python recognizes the backslash '\' as a special escape character that signals a control code rather than ordinary text.

1.3 Python Comments & Code Documentation

Code is read far more often than it is written. Clean, professional code requires meaningful documentation. Python provides two primary mechanisms for documentation: - **Single-Line Comments (`#`)**: Ignored entirely by the interpreter. Used to clarify non-obvious algorithms, mathematical rationales, or implementation caveats. - **Docstrings (`"""..."""`)**: Multi-line documentation strings placed at the top of files, functions, or modules. Python preserves docstrings so they can be read by help tools and other developers.
Statement 4: Commenting Code Effectively

Using single-line comments, inline notes, and docstrings.

# Module: Security Heuristics Core
# Center of Excellence: Data Science & AI

# Baseline risk threshold defined for email quarantine
RISK_CEILING = 75  # Score out of 100

"""
Multi-line docstrings at the top of a script
provide high-level architecture overviews.
"""
print("Active Risk Ceiling:", RISK_CEILING)
Execution walkthrough
  1. 1.Lines 1-2: Ignored by interpreter.
  2. 2.Line 5: Assigns integer 75 to RISK_CEILING; trailing '# Score...' is ignored.
  3. 3.Lines 7-10: Evaluated as a string literal and discarded if unassigned.
  4. 4.Line 11: Emits the variable value.
Expected output
Active Risk Ceiling: 75
Edge cases

• Putting '#' inside a string literal: print('ID #01') will NOT be treated as a comment! The '#' is part of the string: 'ID #01'.

Why it happens: The Python interpreter ignores any text following the '#' symbol on that line, allowing you to add human explanations.

1.4 Arithmetic Operations & Operator Precedence (PEMDAS)

Python functions as an exceptionally powerful computational engine with native support for full mathematical arithmetic. ### The Fundamental Arithmetic Operators: | Operator | Operation | Example | Result | Type Note | | :--- | :--- | :--- | :--- | :--- | | `+` | Addition | `10 + 5` | `15` | int if both int | | `-` | Subtraction | `10 - 4` | `6` | int if both int | | `*` | Multiplication | `6 * 7` | `42` | int if both int | | `/` | True Division | `10 / 2` | `5.0` | **Always returns float** | | `//` | Floor Division | `10 // 3` | `3` | Rounds down to nearest integer | | `%` | Modulo (Remainder) | `10 % 3` | `1` | Remainder after division | | `**` | Exponentiation | `2 ** 8` | `256` | 2 raised to 8th power | ### Order of Operations (PEMDAS): 1. **P**arentheses `()` 2. **E**xponentiation `**` 3. **M**ultiplication `*`, **D**ivision `/`, Floor Division `//`, Modulo `%` (evaluated left-to-right) 4. **A**ddition `+`, **S**ubtraction `-` (evaluated left-to-right)
Statement 5: Arithmetic Operators & True Division vs Floor Division

Contrasting /, //, %, and ** operations.

# True division vs floor division
print("True Division  (14 / 4) :", 14 / 4)
print("Floor Division (14 // 4):", 14 // 4)
print("Modulo         (14 % 4) :", 14 % 4)

# Exponentiation
print("2 to the power 10      :", 2 ** 10)

# Precedence with parentheses
raw_calc = 10 + 5 * 2
grouped  = (10 + 5) * 2
print("10 + 5 * 2              :", raw_calc)
print("(10 + 5) * 2            :", grouped)
Execution walkthrough
  1. 1.Line 2: 14 / 4 evaluates to exact float 3.5.
  2. 2.Line 3: 14 // 4 drops the decimal .5 and returns integer 3.
  3. 3.Line 4: 14 % 4 returns 2 because 14 = (4 * 3) + 2.
  4. 4.Line 7: 2 ** 10 evaluates to 1024.
  5. 5.Line 10: Multiplication (5 * 2 = 10) executes before addition (10 + 10 = 20).
  6. 6.Line 11: Parentheses force addition first (10 + 5 = 15), then multiplication (15 * 2 = 30).
Expected output
True Division  (14 / 4) : 3.5
Floor Division (14 // 4): 3
Modulo         (14 % 4) : 2
2 to the power 10      : 1024
10 + 5 * 2              : 20
(10 + 5) * 2            : 30
Edge cases

• Division by Zero: 10 / 0 or 10 // 0 raises ZeroDivisionError: division by zero. Always guard against zero divisors in financial and statistical formulas. • Negative Floor Division: In Python, -7 // 2 evaluates to -4, NOT -3! Python rounds toward negative infinity (floor), whereas languages like C round toward zero. • Floating-Point Representation: In computers, binary floats cannot represent numbers like 0.1 exactly. 0.1 + 0.2 evaluates to 0.30000000000000004. In scientific computing, never check equality with '==' on raw floats; use math.isclose() or round().

Why it happens: Python enforces strict operator precedence rules identical to standard algebraic conventions.

1.5 Reading Python Error Tracebacks Like an Engineer

Errors are not failures; they are precise diagnostic reports emitted by the Python runtime. Becoming a senior developer means reading error messages calmly and systematically. ### The Two Main Categories of Errors: 1. **Syntax Errors (`SyntaxError`)**: Detected during the parsing phase **before any code runs**. The interpreter encountered an invalid grammatical sequence (missing colon, unmatched quote, invalid character). No lines are executed. 2. **Runtime Exceptions**: The syntax is grammatically valid, but execution fails while running a specific operation (e.g., `ZeroDivisionError`, `NameError`, `TypeError`, `IndexError`). When a traceback occurs, read it **from bottom to top**: the last line states the exact error type and description, while the line above it shows the exact line number where execution failed.
Common Traceback Types in Chapter 1
• SyntaxError: unterminated string literal (Missing closing quote) • NameError: name 'x' is not defined (Using a variable before assigning it) • TypeError: unsupported operand type(s) (e.g. attempting to divide text by a number) • ZeroDivisionError: division by zero (Dividing any number by 0)

Practice exercise

Work through the exercise before starting the chapter assignment

Exercise 1: Emitting Multi-Line Console Output

basic

Modify the starter code to display the official two-line brand name of our organisation, followed by a separator line of 40 hyphens ('-'), and then print the calculation: 2 ** 8.

Chapter 01 assignmentMilestone

Financial Ledger & Hardware Spec Terminal Formatter

Scenario

A high-performance computing node deployed at the Center of Excellence needs an automated boot banner and financial compute budget report. You have been tasked with generating a clean ASCII terminal report using only the arithmetic statements and print formatting techniques learned in Chapter 1.

Implementation requirements
  • Print an ASCII top header: '=== CENTER OF EXCELLENCE HPC CLUSTER ==='
  • Define variables for total budget ($50,000), hardware costs ($34,500), and operational electricity rate ($0.12 per kWh for 15,000 kWh).
  • Compute the total electricity cost using multiplication (*).
  • Compute the remaining unallocated balance by subtracting hardware and electricity costs from total budget.
  • Calculate the daily compute cost assuming a 30-day billing cycle using true division (/).
  • Print each ledger item using multi-argument print() with custom separators (' : ') and format financial figures clearly.
  • Verify that remaining budget does not trigger negative numbers or zero-division.
Edge cases to handle
  • 1.Floating-point accuracy: Ensure electricity costs (15000 * 0.12) resolve to expected monetary figures.
  • 2.Zero-division prevention: Ensure cycle days is non-zero before dividing.
  • 3.Clean spacing: Avoid accidental double spaces when combining string labels with numeric values.
Starter template
# Chapter 1 Assignment: HPC Compute Ledger Formatter
# Center of Excellence: Data Science & AI

# 1. Header Banner
print("=" * 40)
print("=== CENTER OF EXCELLENCE HPC CLUSTER ===")
print("=" * 40)

# 2. Financial Figures
total_budget = 50000
hardware_cost = 34500
kwh_used = 15000
kwh_rate = 0.12
billing_days = 30

# TODO: Compute electricity_cost = kwh_used * kwh_rate
# TODO: Compute total_spent = hardware_cost + electricity_cost
# TODO: Compute remaining_budget = total_budget - total_spent
# TODO: Compute daily_burn_rate = total_spent / billing_days

# TODO: Print formatted ledger using sep=" : "
Progressive hints

Chapter summary

Key concepts and syntax cards for review

Key concepts
  • 01Python is an interpreted language that executes statements sequentially from top to bottom.
  • 02print() emits strings to stdout and accepts 'sep' (inter-item delimiter) and 'end' (trailing character, default newline).
  • 03Arithmetic operators follow PEMDAS precedence: parentheses override standard order; true division (/) always yields float.
  • 04Floor division (//) truncates down toward negative infinity; modulo (%) computes the remainder.
  • 05Tracebacks pinpoint the failure line: read from bottom to top to identify the error class and explanation.
Syntax reference
print("Text", val, sep=" | ", end="\n")Console output with custom delimiters and termination.
val = a + b * (c ** d) // eArithmetic expression adhering to PEMDAS operator precedence.
# CommentarySingle-line comment ignored by the Python interpreter.

Knowledge check

Verify your grasp of the chapter concepts

What will be printed by the statement: print('Python', 'AI', sep='_', end='!')?

What is the output of the mathematical expression: 10 + 2 * 3 ** 2?

Which error occurs if you write: print(10 / (5 - 5))?