1. Introduction to Code Execution Modes in Python
In software engineering, understanding how code is supplied to an execution engine is fundamental. Python provides two primary operational modes for executing code:
- Interactive Mode (The REPL): An interactive command-line environment that reads, evaluates, and prints Python code instantly line-by-line.
- Script Mode (Source Files): Writing Python code in persistent files (ending with a
.pyextension) and running the complete script through the Python interpreter.
While interactive mode is excellent for quick testing, API exploration, and debugging, script mode is where production software, web applications, data pipelines, and automation scripts are built and preserved.
2. Deep Dive: What is the Python REPL?
The acronym REPL stands for Read - Eval - Print - Loop. It represents an interactive shell environment that processes code in a continuous four-stage lifecycle:
| REPL Stage | Underlying Internal Process |
|---|---|
| 1. Read | The shell accepts user input in Python syntax at the interactive prompt (>>>) and parses it into memory. |
| 2. Eval (Evaluate) | The Python Virtual Machine (PVM) compiles and evaluates the code statement or expression immediately. |
| 3. Print | If the expression produces a result, the REPL formats and displays the returned value directly to standard output. |
| 4. Loop | The shell resets its state and waits for the user to input the next Python command. |
Launching and Interacting with the REPL
To start the Python REPL on any system:
- Open Terminal (macOS/Linux) or Command Prompt / PowerShell (Windows).
- Type
python(orpython3on macOS/Linux) and press Enter. - You will see system configuration details followed by the primary prompt symbol:
>>>.
Python 3.12.0 (main, Oct 10 2023, 15:12:10) [GCC 11.2.0 on linux] on linux Type "help", "copyright", "credits" or "license" for more information. >>>
Executing Expressions in the REPL
In the REPL, you do not always need an explicit print() function to see the result of mathematical calculations or variable evaluations:
>>> 5 + 10 15 >>> name = "Python Engineer" >>> name 'Python Engineer' >>> len(name) 15
exit() or quit() and press Enter. Alternatively, press Ctrl + Z then Enter (Windows) or Ctrl + D (macOS/Linux).
3. Interactive Practice: Live Code Execution Examples
Below are interactive compiler-style code blocks reflecting actual Python execution inside script environments.
Practice Box 1: Simple Output and String Printing
print("Hello, World!")
print("Welcome to Professional Python Development!")
Hello, World! Welcome to Professional Python Development!
Practice Box 2: Working with Arithmetic and Variables
item_price = 120
quantity = 3
total = item_price * quantity
print("Total:", total)
Total: 360
Practice Box 3: Formatted Strings and Dynamic Calculations
hours_worked = 40
hourly_rate = 25.50
gross_pay = hours_worked * hourly_rate
print(f"Gross Pay: ${gross_pay:.2f}")
Gross Pay: $1020.00
4. Writing Your First Persistent Script File
While the REPL is efficient for isolated testing, code disappears as soon as the session closes. To write reusable programs, save code into text files with a .py extension using VS Code.
Step-by-Step Script Workflow in VS Code
- Open VS Code and ensure your workspace folder (e.g.,
python_mastery_course/lesson_03/) is loaded in the Explorer sidebar. - Create a new file and name it
main.py. - Enter the following standard Python program code:
# main.py - First Python Script
user_name = "Developer"
course_title = "Python Mastery"
print("--- System Initialization ---")
print(f"User: {user_name}")
print(f"Course: {course_title}")
print("Status: Ready to write code.")
- Save the file (Ctrl + S / Cmd + S).
- Open the VS Code integrated terminal (Ctrl + `).
- Run the script by typing:
python main.py
5. Anatomy of the `print()` Built-In Function
The print() function is Python's standard primary output mechanism. It accepts multiple parameters that control how data displays in the console.
Signature of the `print()` Function:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Key Arguments Explained:
- `*objects`: One or more values, variables, or expressions separated by commas.
- `sep` (Separator): Specifies the character inserted between multiple objects. The default is a single space (
' '). - `end` (End character): Specifies what is printed at the end of the line. The default is a newline character (
'\n').
Advanced `print()` Code Demonstrations
# Custom separators
print("2026", "07", "25", sep="-")
# Custom end characters (preventing newlines)
print("Processing", end="... ")
print("Done!")
2026-07-25 Processing... Done!
6. Understanding Early Execution Errors
Beginning developers encounter execution errors. Recognizing error types early builds confidence and improves debugging speed.
1. SyntaxError
Occurs when the code violates Python's grammar rules during the compilation phase before execution starts.
# Invalid Code (Missing closing string quote):
print("Hello World)
# System Error Raised:
SyntaxError: unterminated string literal
2. NameError
Occurs at runtime when trying to evaluate a variable or function name that has not been defined.
# Invalid Code (Variable misspelled): user_score = 100 print(usr_score) # System Error Raised: NameError: name 'usr_score' is not defined. Did you mean: 'user_score'?
total, Total, and TOTAL are treated as three separate variables in memory. Built-in keywords must be lowercase (e.g., print() is correct; Print() raises a NameError).
7. Frequently Asked Interview Questions with Answers
.py scripts) saved on disk, allowing long-term code storage, version control, and multi-file application execution.
sep (separator) parameter defines the string inserted between multiple comma-separated arguments inside print(). By default, sep=' ' (a single space). Changing it (e.g., sep='-') changes how items join in the output stream.
print() function (e.g., print(10 + 20)).
SyntaxError is detected by the compiler before script execution begins due to invalid code structure. A runtime error like NameError occurs mid-execution when validly structured code references an undefined variable during runtime execution.
8. Homework & Practical Assignment
Task 1: REPL Exploration
Open your system terminal, launch the Python REPL, and complete the following:
- Evaluate the expression:
(25 * 4) + (100 / 2)directly in the REPL. - Assign your name to a variable
student_nameand inspect its length usinglen(student_name). - Exit the REPL using
exit().
Task 2: Script Creation & Formatting
In VS Code, create a file named receipt.py inside your lesson_03 directory. Write a program that calculates total costs with taxes:
- Define
subtotal = 250andtax_rate = 0.18. - Calculate
tax_amount = subtotal * tax_rateandfinal_total = subtotal + tax_amount. - Print output formatted cleanly using custom
sepandendparameters.
Task 3: Error Diagnostic Exercise
Type the following broken script into VS Code, run it, record the exact error message raised by the terminal, and fix the script:
# Broken code for diagnostic task
UserScore = 50
print("User score is:", userscore)
9. File & Workspace Directory Structure
Directory Architecture Standard:
Organize your course workspace following this clean layout:
python_mastery_course/
│
├── lesson_01/
│ └── homework_submission.md
│
├── lesson_02/
│ └── environment_setup_verification.txt
│
└── lesson_03/
├── hello.py
├── bill.py
├── calculator.py
├── print_formats.py
└── receipt.py
10. What We Will Learn Next
```
OnlineCBT