Skip to content
Sign inGet all access
Chapter 1·10 minFree

Getting Started

Running code, indentation, printing, and what counts as true.

Run a file, run the REPL

Two ways to run Python. A file:

hello.py
print("Hello from a file")
OutputHello from a file
python hello.py

And the REPL, which you start by typing python with no arguments:

REPL session
>>> 1 + 2
>>> "abc" * 2
Output3'abcabc'

Significant whitespace

Indentation is not a style choice in Python. It is the block structure — there are no braces, and no semicolons. Four spaces per level, and mixing tabs with spaces is a TabError, not a warning.

x = 10

if x > 5:
    print("big")
    print("done")
Outputbigdone

Both print calls are inside the if because both are indented. Dedent, and the line leaves the block:

x = 10

if x > 5:
    print("big")
print("always runs")
Outputbigalways runs

print takes any number of arguments and separates them with a space:

print("a", "b", "c")
print("a", "b", "c", sep="-")
print("no newline here", end="")
Outputa b ca-b-cno newline here

String interpolation uses an f prefix. Anything inside curly braces is an expression:

name, age = "Ada", 36

print(f"{name} is {age}")
print(f"Next year: {age + 1}")
print(f"Pi is {3.14159:.2f}")
OutputAda is 36Next year: 37Pi is 3.14

Comments and docstrings

# comments to end of line. There is no block comment syntax.

# this is a comment
x = 42  # so is this
print(x)
Output42

A string literal as the first statement of a file is a docstring — a real object attached to the thing it documents:

orders.py
"""Tools for working with orders."""

print(__doc__)
OutputTools for working with orders.

if __name__ == “__main__”

You will see this at the bottom of nearly every Python script:

greet.py
print("always runs")

if __name__ == "__main__":
    print("only when run directly")
Outputalways runsonly when run directly

Python sets the variable __name__ to "__main__" when a file is run directly, and to the module’s name when it is imported. So the guarded line runs on python greet.py, but not on import greet — while the unguarded line runs either way.

Truthiness

Every object has a truth value. Empty containers, zero and None are falsy:

print(bool([]))
print(bool(""))
print(bool(0))
print(bool(None))
OutputFalseFalseFalseFalse

Everything else is truthy:

print(bool([1]))
print(bool("a"))
print(bool(42))
OutputTrueTrueTrue

Which means you check for an empty list directly, not by its length:

items = []

if not items:
    print("nothing to do")
Outputnothing to do