Logo OnlineCBT
PYTHON Tutorial
PYTHON · LESSON 3

Your First Python Program and the REPL

Learn the difference between interactive experiments and saved programs while examining how Python executes statements.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive
Updated: 26 Jul 2026


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:

  1. Interactive Mode (The REPL): An interactive command-line environment that reads, evaluates, and prints Python code instantly line-by-line.
  2. Script Mode (Source Files): Writing Python code in persistent files (ending with a .py extension) 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:

  1. Open Terminal (macOS/Linux) or Command Prompt / PowerShell (Windows).
  2. Type python (or python3 on macOS/Linux) and press Enter.
  3. 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
Exiting the REPL: To exit the interactive shell and return to your operating system prompt, type 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

HELLO.PY
print("Hello, World!")
print("Welcome to Professional Python Development!")
OUTPUT
Hello, World!
Welcome to Professional Python Development!

Practice Box 2: Working with Arithmetic and Variables

BILL.PY
item_price = 120
quantity = 3
total = item_price * quantity
print("Total:", total)
OUTPUT
Total: 360

Practice Box 3: Formatted Strings and Dynamic Calculations

CALCULATOR.PY
hours_worked = 40
hourly_rate = 25.50
gross_pay = hours_worked * hourly_rate
print(f"Gross Pay: ${gross_pay:.2f}")
OUTPUT
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

  1. Open VS Code and ensure your workspace folder (e.g., python_mastery_course/lesson_03/) is loaded in the Explorer sidebar.
  2. Create a new file and name it main.py.
  3. 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.")
  1. Save the file (Ctrl + S / Cmd + S).
  2. Open the VS Code integrated terminal (Ctrl + `).
  3. 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

PRINT_FORMATS.PY
# Custom separators
print("2026", "07", "25", sep="-")

# Custom end characters (preventing newlines)
print("Processing", end="... ")
print("Done!")
OUTPUT
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'?
Case Sensitivity Warning: Python is strictly case-sensitive. Variable names like 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

Q1: What is the REPL in Python, and when should a developer use it?
Answer: The REPL (Read-Eval-Print Loop) is Python's interactive command-line shell. It reads Python statements, evaluates them, prints outputs, and loops back for further input. Developers use the REPL for rapid prototyping, quick mathematical calculations, testing built-in functions, and inspecting module documentation.
Q2: What is the difference between interactive mode and script mode in Python?
Answer: Interactive mode executes commands immediately line-by-line in the terminal without saving the session. Script mode reads complete program files (.py scripts) saved on disk, allowing long-term code storage, version control, and multi-file application execution.
Q3: How does the `sep` parameter work in the `print()` function?
Answer: The 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.
Q4: Why does entering `10 + 20` display `30` in the REPL but output nothing inside a script file?
Answer: The REPL automatically evaluates expressions and prints their return values as part of its "Print" stage. Inside a script file, evaluation occurs quietly in memory unless explicitly passed to the print() function (e.g., print(10 + 20)).
Q5: What is the difference between a `SyntaxError` and a runtime error like `NameError`?
Answer: A 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:

  1. Evaluate the expression: (25 * 4) + (100 / 2) directly in the REPL.
  2. Assign your name to a variable student_name and inspect its length using len(student_name).
  3. 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 = 250 and tax_rate = 0.18.
  • Calculate tax_amount = subtotal * tax_rate and final_total = subtotal + tax_amount.
  • Print output formatted cleanly using custom sep and end parameters.

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

Next Up: Lesson 4 — Syntax, Indentation and Comments

Now that you can run scripts and use the REPL, we will master Python's unique structural rules.

In the next lesson, we will cover:

  • Python's strict block structuring using Indentation (4-space standard vs tabs).
  • Single-line comments (#) and multi-line docstrings ("""...""").
  • Understanding IndentationError and how to prevent visual layout bugs.
  • Statement multi-lining using backslashes (\) and implicit parenthetical continuation.

```

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
Address Contact

+91 7877547686

E-mail

onlinecbtportal@gmail.com

Helpline Number

+91 7877547686


Click To Download
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat