Chapter 1 Β· Getting Started

Meet Python & the Interpreter

Install Python 3.15, run your first lines in the interactive prompt, and learn the two ways every Python program is run.

You will learn

  • What Python is good at, and how it differs from Java and JavaScript.
  • How to start the interpreter, run a script, and quit.
  • How to read command-line arguments with sys.argv.
  • How the interactive prompt (the REPL) works, including >>>, ... and help().
  • Source-file encoding, the shebang line, and the interactive startup file.

Why Python?

Python is a general-purpose language that is famous for being easy to read. Code often looks like pseudo-code. It is used for scripting, web back-ends, data science, automation, testing and teaching.

The language is named after the comedy group Monty Python, not the snake. That is why the docs use the words spam and eggs in their examples. This book uses them too, sometimes.

Three things make Python feel different from Java:

Java

Python

β˜• Java / 🟨 JS: Python is much closer to JavaScript in spirit (dynamic, no compile step, functions are values) but closer to Java in strictness: "1" + 1 is an error in Python, not "11". Python does not quietly convert types for you.

Installing Python 3.15

This book uses Python 3.15 (released October 2026). Older versions can't run some examples, like match in Chapter 4 or the comprehension unpacking in Chapter 6.

Ways to get it:

OptionHowGood for
Official installerDownload from python.org/downloadsWindows and macOS beginners
uvuv python install 3.15Keeping several versions side by side, no admin rights
Package managerHomebrew, apt, winget…People who already use one

Then check the version in a terminal:

⚠️ Pitfall: on macOS and Linux the command is usually python3. A plain python might not exist, or might be an old system copy. On Windows, the installer gives you py (the Python launcher) and python. This book writes python3.

Starting the interpreter

The interpreter is the program that reads and runs Python code. You can use it in two ways.

1. Interactive mode (the REPL)

Type python3 with no file name. You get a prompt where you type one statement at a time and see the result right away. REPL means Read–Eval–Print Loop: it reads your line, evaluates it, prints the result, and loops.

The primary prompt >>> asks for a new statement. The secondary prompt ... appears when a statement continues onto more lines, such as an if block.

Notes on that session:

To quit: type exit (or quit), or press Ctrl+D on macOS/Linux, or Ctrl+Z then Enter on Windows.

2. Running a script

Save code in a file ending in .py and pass the file name:

Two more ways to start Python, which you will use later:

CommandWhat it doesExample
python3 file.pyRuns a script filepython3 hello.py
python3 -c "code"Runs a short piece of code given as a stringpython3 -c "print(2**10)"
python3 -m moduleFinds a module by name and runs it as a scriptpython3 -m venv .venv (Chapter 15)
python3 -i file.pyRuns the script, then stays in the REPL so you can inspect variablespython3 -i hello.py

Passing arguments to a script

Words typed after the script name are command-line arguments. Python puts them in a list called sys.argv, inside the sys module. To use it you must import sys first. (Modules are covered in Chapter 8; for now, import just means "load this toolbox".)

β˜• Java: in Java, args[0] is the first user argument. In Python, sys.argv[0] is the script name, and the user's first argument is sys.argv[1]. 🟨 Node: this is like process.argv.slice(1).

πŸ’‘ Tip: all arguments arrive as strings. python3 add.py 2 3 gives you "2" and "3". Convert them with int() before doing maths. For real tools, the argparse module (Chapter 13) parses arguments for you.

Getting around in the REPL

The interactive prompt is the best place to experiment. Since Python 3.13 it has a modern editor built in:

Two built-in helpers you will use all the time:

help(len) shows the documentation for len, and dir("hi") lists everything you can do with a string. Try them in your own REPL; press q to leave the help viewer.

In the REPL, the special name _ holds the last printed result:

⚠️ Pitfall: _ only works in the interactive prompt. Don't use it in scripts, and never assign to it yourself in the REPL, or it stops updating.

πŸ“ Older syntax you'll still see: in Python 2, print was a statement: print "hi". In Python 3 it is a function: print("hi"). Python 2 reached its end of life in 2020. If a tutorial writes print "hi", it is very out of date.

Source code encoding

A text file is stored as bytes. An encoding is the rule that turns those bytes back into characters. Python reads .py files as UTF-8 by default. UTF-8 can store every character: accents, Greek, emoji.

If a file is saved in another encoding, you can declare it with a special comment on the first or second line, for example # -*- coding: cp1252 -*-. You will rarely need this. Save your files as UTF-8 and skip the line.

πŸ“ New in 3.15: Python now also uses UTF-8 by default when it reads and writes files with open(), no matter what your computer's locale is (PEP 686). Chapter 9 explains why you should still write encoding="utf-8".

Executable scripts and the shebang line

On macOS and Linux, you can run a script directly (./tool.py) instead of typing python3 tool.py. You need two things:

  1. A shebang line as the very first line. It tells the operating system which program runs the file.
  2. Permission to execute the file: chmod +x tool.py.

On Windows, the py launcher reads the shebang line too, and .py files are linked to Python by the installer.

The interactive startup file

If you always import the same modules when you open the REPL, you can automate it. Point the PYTHONSTARTUP environment variable at a Python file. Python runs that file each time an interactive session starts. Scripts ignore it.

There are also sitecustomize and usercustomize modules, which run at startup for every program, scripts included. They are for advanced setups, so you can ignore them for now.

Your first error message

Errors in Python are called exceptions (Chapter 10). When one is not handled, Python prints a traceback: the chain of calls that led to the error, with the cause on the last line. Always read a traceback from the bottom up.

The last line names the error type (TypeError) and explains it: you cannot glue a string and a number together. Fix it with str(6), a comma in print, or an f-string (Chapter 9).

❌ Wrong

βœ… Right

More examples

1. A tiny calculator script that reads arguments

2. Exploring an unknown object in the REPL

3. One-liners with -c

Notice that Python integers have no size limit: 2 ** 100 just works. Java's long would overflow.

4. Checking the version from inside a script

5. Using -i to poke at a script's variables

Recap

  • Python is interpreted, dynamically typed, and uses indentation for blocks.
  • python3 opens the REPL (>>> and ... prompts). python3 file.py runs a script.
  • sys.argv is a list of strings. Item 0 is the script name.
  • The REPL echoes expression values. Scripts need print().
  • Source files are UTF-8 by default. A shebang plus chmod +x makes a script executable.
  • Read tracebacks from the bottom line up.

Exercises

Get the playground: git clone https://github.com/coder-hop/python-book-playground.git playground clones coder-hop/python-book-playground into a folder named playground/ (or simply create an empty playground/ folder yourself; Using the Playground has the details). Exercises marked playground add files there. Chapter 16 grows them into a full project.

Exercise 1 🟒 easy build it · playground

Create playground/hello.py that prints Hello, Python 3.15!. Run it from the terminal.

Show solution

Run it with python3 playground/hello.py. One line is a complete program: there is no class or main to write.

Exercise 2 🟒 easy predict the output

You type these lines into the REPL. Which lines print something, and what?

Show solution

Only the expression lines echo: x * 3 shows 30 and y shows 11. Assignments print nothing. Run as a script, the same code prints nothing at all, because scripts never echo values.

Exercise 3 🟒 easy fix the bug

This prints an error. Fix it two different ways.

Show solution

Python never converts types silently. + between a str and an int is a TypeError.

Exercise 4 🟒 easy explain why

A friend's script show.py does print(sys.argv[1]) and crashes with IndexError when run as python3 show.py. Why?

Show solution

With no extra words, sys.argv is ['show.py'], a list with one item, at index 0. There is no index 1, so Python raises IndexError. Check len(sys.argv) first, or use sys.argv[1:], which is just empty instead of crashing.

Exercise 5 🟑 medium build it · playground

Create playground/args.py that prints how many arguments it got (not counting the script name), then prints each one on its own line with its position, like 1: apple.

Show solution

sys.argv[1:] skips the script name. Chapter 7 shows enumerate(), which removes the manual counter.

Exercise 6 🟑 medium predict the output

What does python3 add.py 4 5 print (the script is from "More examples" #1)? And what does python3 add.py four 5 do?

Show solution

The first prints 4 + 5 = 9. The second crashes with ValueError: invalid literal for int() with base 10: 'four', because int() can only convert strings of digits. Chapter 10 shows how to catch this error politely.

Exercise 7 🟑 medium build it

Using only python3 -c, print how many seconds are in a (non-leap) year.

Show solution

-c runs the string as a tiny script, so you need print. There is no automatic echo like in the REPL.

Exercise 8 🟑 medium fix the bug

This file was pasted from a website and fails with IndentationError. What is wrong, and what is the fix?

Show solution

In Python, indentation is the block. A line ending in : must be followed by at least one indented line. Use 4 spaces per level.

Exercise 9 πŸ”΄ hard build it Β· playground

Create an executable playground/version.py with a shebang. It should print OK if Python is 3.15 or newer, and otherwise print Too old: X.Y and stop with exit code 1. Run it as ./version.py, then check the exit code with echo $?.

Show solution

chmod +x playground/version.py makes it runnable. Tuples compare item by item, so (3, 9) < (3, 15) is True. Comparing the strings "3.9" and "3.15" would give the wrong answer. Exit codes are covered in Appendix B.

Exercise 10 πŸ”΄ hard mini-project Β· playground

Create playground/tip.py. It takes a bill amount and an optional tip percentage (default 15), and prints the tip and the total. python3 tip.py 40 20 should print Tip: 8.0 and Total: 48.0. With no arguments, it prints a usage line instead of crashing.

Show solution

It combines this chapter's pieces: reading sys.argv, converting strings to numbers, and checking the argument count. The X if cond else Y form is a conditional expression (Chapter 3).

Official docs