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.
- 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
1.2 How Python Runs Your Code
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")- 1.Line 2: The interpreter parses the string literal "Center of Excellence..." and emits it to stdout with a trailing newline.
- 2.Line 3: The integer literal 2026 is converted to its string representation '2026' and output.
- 3.Line 4: Emits the third line and flushes the buffer.
Center of Excellence: Data Science & Artificial Intelligence 2026 Workshop 01: Python Foundations
• 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.
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]")- 1.Line 2: Outputs each string separated by ' | ' instead of spaces.
- 2.Line 3: Outputs strings and numbers separated by ' -> '.
- 3.Line 6: Sets end='... ', keeping the console cursor on the same line.
- 4.Line 7: Appends 'READY [OK]' immediately on the same line.
Node | Weight | Bias Alpha -> 0.85 -> 0.12 Initializing security scanner... READY [OK]
• 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.
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\"")- 1.Lines 2-4: Assigns a multi-line string containing raw newlines to the variable 'report'.
- 2.Line 5: Prints the multi-line string preserving exact visual layout.
- 3.Line 8: Interprets '\t' as tab indentation, '\n' as newline, and '\"' as literal quotation marks.
[SYSTEM REPORT] Status : Active Cluster: CoE-Alpha-01 Security Metric: 98.5% Verdict: "CLEAN"
• 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
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)- 1.Lines 1-2: Ignored by interpreter.
- 2.Line 5: Assigns integer 75 to RISK_CEILING; trailing '# Score...' is ignored.
- 3.Lines 7-10: Evaluated as a string literal and discarded if unassigned.
- 4.Line 11: Emits the variable value.
Active Risk Ceiling: 75
• 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)
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)- 1.Line 2: 14 / 4 evaluates to exact float 3.5.
- 2.Line 3: 14 // 4 drops the decimal .5 and returns integer 3.
- 3.Line 4: 14 % 4 returns 2 because 14 = (4 * 3) + 2.
- 4.Line 7: 2 ** 10 evaluates to 1024.
- 5.Line 10: Multiplication (5 * 2 = 10) executes before addition (10 + 10 = 20).
- 6.Line 11: Parentheses force addition first (10 + 5 = 15), then multiplication (15 * 2 = 30).
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
• 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
Practice exercise
Work through the exercise before starting the chapter assignment
Exercise 1: Emitting Multi-Line Console Output
basicModify 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.
Financial Ledger & Hardware Spec Terminal Formatter
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.
- 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.
- 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.
# 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=" : "
Chapter summary
Key concepts and syntax cards for review
- 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.
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))?