Warming up the neural circuits...
By the end of this chapter you will:
Every programming journey starts with one step: writing code that does something visible. In Python, that's print("Hello, world!"). It's a cliché for a reason — it proves your setup works, and it gives you a feedback loop: write code, run it, see what happens.
This chapter teaches you two ways to run Python — script files and the REPL — and how to read the output (and the errors). By the end, you'll be able to write, run, and debug simple programs.
Before diving into code, understand how Python runs your programs:
Run from file: python hello.py
When you run python hello.py:
Best for: Programs you want to save, share, or run again. Scripts, applications, automation.
Run interactively: python (no file)
The REPL (Read-Eval-Print Loop) is an interactive shell:
Best for: Quick experiments, testing ideas, learning.
Error messages: Read bottom-up.
When Python encounters an error, it shows a traceback. Read it bottom-up:
NameError: name 'x' is not defined - the error type and messageFile "hello.py", line 2 - where the error happenedprint(x) with ^ pointing to the problemCommon errors:
NameError - variable does not existSyntaxError - invalid Python syntaxTypeError - wrong type (for example, adding string + int)IndentationError - bad indentationThink of Python like a translator:
1. Script files — You write code in a .py file and run it with python filename.py. The interpreter reads the file from top to bottom, executes each line, and exits.
2. The REPL — You type code interactively in the terminal, and Python executes each line immediately. The REPL is great for experimenting; script files are for programs you want to save and reuse.
When to use each:
Create a file called hello.py:
# hello.py
print("Hello, world!")Run it from the terminal:
$ python hello.py
Hello, world!That's it. You just wrote and ran your first Python program.
What happened:
hello.pyprint("Hello, world!"), which outputs the text to the terminalThe print() function outputs text to the terminal. But it's more flexible than most beginners realize.
Basic usage:
print("Hello, world!")
# Hello, world!Multiple arguments:
print("Name:", "Alice", "Age:", 30)
# Name: Alice Age: 30By default, print() separates arguments with a space. You can change this with the sep parameter:
print("2024", "01", "15", sep="-")
# 2024-01-15The end parameter:
By default, print() adds a newline at the end. You can change this:
print("Hello", end=" ")
print("world!")
# Hello world!f-strings (a preview):
f-strings let you embed variables directly in strings. We'll cover them in depth in Chapter 5, but here's a taste:
name = "Alice"
age = 30
print(f"Name: {name}, Age: {age}")
# Name: Alice, Age: 30The f before the string means "formatted string". The {name} and {age} are replaced with the variable values.
Open the REPL by running python (Windows) or python3 (macOS/Linux) in the terminal. You'll see a >>> prompt.
>>> 2 + 2
4
>>> print("Hello")
Hello
>>> name = "Alice"
>>> print(f"Hello, {name}!")
Hello, Alice!
>>> exit()Key behaviors:
2 + 2 outputs 4 without needing print().name = "Alice" doesn't output anything — it just creates the variable.name = "Alice", you can use name in later commands.When to use the REPL:
When NOT to use the REPL:
Comments are text in your code that Python ignores. They're for humans — explanations, reminders, or notes to future-you.
Single-line comments start with #:
# This is a comment
print("Hello") # This is an inline commentMulti-line comments use """ or ''' (triple quotes). These are technically string literals, but they're commonly used as multi-line comments:
"""
This is a multi-line comment.
It spans several lines.
Python ignores it.
"""
print("Hello")Docstrings are a special kind of multi-line comment that documents functions, classes, or modules. We'll cover them in Chapter 8.
When to comment:
When NOT to comment:
x = 5 # Set x to 5 is uselessErrors are inevitable. The good news: Python's error messages (called tracebacks) are detailed and helpful. The bad news: they look scary at first.
Let's break one down. Create a file with a bug:
# bug.py
print("Hello")
print(x) # x is not defined
print("World")Run it:
$ python bug.py
Hello
Traceback (most recent call last):
File "bug.py", line 2, in <module>
print(x)
^
NameError: name 'x' is not definedHow to read a traceback (bottom-up):
NameError: name 'x' is not defined.File "bug.py", line 2 tells you the error is on line 2 of bug.py.print(x) shows the line that caused the error. The ^ points to the problematic part.Common error types you'll see:
| Error | What it means |
|---|---|
NameError | You used a variable that doesn't exist |
SyntaxError | Your code has invalid syntax (missing parenthesis, typo, etc.) |
TypeError | You used the wrong type (e.g., adding a string and an int) |
IndentationError | Your indentation is wrong (mixed tabs and spaces) |
ModuleNotFoundError | You tried to import a module that isn't installed |
Scripting: System administrators use Python scripts to automate tasks. A simple backup script might look like:
# backup.py
import shutil
import datetime
today = datetime.date.today()
backup_name = f"backup_{today}.zip"
shutil.make_archive(backup_name, "zip", "/path/to/data")
print(f"Backup created: Data processing: Data scientists use scripts to process CSV files:
# process.py
import csv
with open("data.csv") as f:
reader = csv.DictReader(f)
for row in reader:
print(f"Name: {row['name']}, Age: Web scraping: Developers use Python to extract data from websites (with the requests and BeautifulSoup libraries).
| Mistake | Why it's wrong | Fix |
|---|---|---|
SyntaxError: invalid syntax on print "hello" | Python 2 syntax. Python 3 requires parentheses. | Use print("hello") |
NameError: name 'x' is not defined | You used a variable before assigning it a value. | Assign the variable first: x = 5 |
IndentationError: unexpected indent | Python uses indentation to define code blocks. Mixed tabs and spaces break this. | Use 4 spaces per indent level, never tabs |
| Forgetting to save the file before running | Python runs the file on disk, not the unsaved changes in your editor. | Save the file (Ctrl+S) before running |
Running python script.py in the wrong directory | Python can't find the file if you're not in the same directory. | Use cd to navigate to the folder containing the file, or use the full path |
Logging vs print: In production code, use the logging module instead of print(). Logging lets you control output levels (DEBUG, INFO, WARNING, ERROR) and write to files. We'll cover it in L5.
Encoding: Python 3 uses UTF-8 by default, so you can print Unicode characters (emojis, accented letters, etc.) without issues. If you see UnicodeEncodeError, check your terminal's encoding settings.
Shebang lines: On macOS/Linux, you can make a Python script executable by adding a shebang line at the top:
#!/usr/bin/env python3
print("Hello")Then run chmod +x script.py and execute it with ./script.py. This is optional — you can always run it with python3 script.py.
greeting.py that prints your name and age on separate lines.x = 10, y = 20, x + y, print(x + y). What's the difference?x=10, y=20, x+y, print(x+y)error.py with print("Hello") then print(message). What error do you see? Fix it.print("Hello"), print(message)datetime module.datetime.date.today()Beginner:
"What's the difference between running Python in the REPL vs a script file?"
The REPL is interactive — you type code and see results immediately. It's great for experiments. Script files are saved
.pyfiles that you run withpython filename.py. They're for programs you want to save, share, or run again.
"How do you read a Python traceback?"
Start at the bottom — the last line shows the error type and message (e.g.,
NameError: name 'x' is not defined). The line above shows the file and line number where the error occurred. Work upward if the error happened inside a function.
Senior:
"What's the difference between print(x) and just x in the REPL?"
In the REPL, both produce the same output for simple values.
xalone evaluates the expression and the REPL prints the result.print(x)explicitly calls thefunction. In a script file, alone doesn't print anything — you need .
python file.py) for saved programs, REPL for experiments.print() outputs text. Use sep to change separators, end to change the line ending, and f-strings for formatting.#) are for humans. Explain why, not what.NameError (undefined variable), SyntaxError (invalid syntax), IndentationError (bad indentation).I want to…
├── Run a script → python file.py
├── Open the REPL → python (or python3)
├── Print text → print("Hello")
├── Format output → print(f"Name: {name}")
├── Add a comment → # This is a comment
└── Read an error → Start at the bottom of the tracebackWhat are the two ways to run Python code?
xprint(x)"Why is print() not suitable for production logging?"
print()always outputs to stdout with no control over levels, formatting, or destinations. Theloggingmodule lets you set levels (DEBUG, INFO, WARNING, ERROR), format output, write to files, and integrate with monitoring systems. In production, you need structured logs, not rawprint()output.