Chapter 1: Getting Started

Your first Python program. Verify your environment works, then move on.

Verify Python

python3 --version

Need 3.9+. If not installed:

# Debian/Ubuntu
sudo apt install python3 python3-pip

# Fedora
sudo dnf install python3

# Arch
sudo pacman -S python

The REPL

Python’s interactive interpreter. Start it:

python3

You see the prompt >>>. Type Python, get results:

>>> 2 + 2
4
>>> print("Hello from the REPL")
Hello from the REPL
>>> exit()

Use the REPL to test ideas quickly. Exit with exit() or Ctrl+D.

Your First Script

Create hello.py:

print("Hello, Python")

Run it:

python3 hello.py

Output:

Hello, Python

That’s it. If this works, your environment is ready.

What Happened

When you run python3 hello.py:

  1. Python reads the file

  2. Parses each line as Python code

  3. Executes print() - a built-in function

  4. print() outputs the string to stdout

The .py extension is convention, not required. Python doesn’t care.

Running Scripts Directly

Make scripts executable:

chmod +x hello.py

Add a shebang as the first line:

#!/usr/bin/env python3
print("Hello, Python")

Now run directly:

./hello.py

Troubleshooting

If something breaks, Python gives you a traceback:

print("Hello)  # missing quote
  File "hello.py", line 1
    print("Hello)
          ^
SyntaxError: unterminated string literal

Read tracebacks bottom-up: 1. Error type (SyntaxError) 2. Line number and file 3. The problematic code with ^ pointing to the issue

Exercises

1-1. REPL Math

Open the REPL. Calculate: - 365 * 24 * 60 (minutes in a year) - 2 ** 10 (2 to the 10th power) - 17 / 3 vs 17 // 3 (division vs floor division)

1-2. Script It

Create minutes.py that prints the number of minutes in a week.

1-3. Break It

Intentionally create syntax errors. Learn to read tracebacks: - Missing parenthesis - Missing quote - Misspelled print

Summary

  • python3 starts the REPL for quick tests

  • .py files are scripts, run with python3 script.py

  • Tracebacks tell you what broke and where

  • When in doubt, read the error message

Next: Variables and data types.