Getting Started
Running code, indentation, printing, and what counts as true.
Run a file, run the REPL
Two ways to run Python. A file:
print("Hello from a file")python hello.py
And the REPL, which you start by typing python with no arguments:
>>> 1 + 2
>>> "abc" * 2Significant 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")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")print() and f-strings
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="")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}")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)A string literal as the first statement of a file is a docstring — a real object attached to the thing it documents:
"""Tools for working with orders."""
print(__doc__)if __name__ == “__main__”
You will see this at the bottom of nearly every Python script:
print("always runs")
if __name__ == "__main__":
print("only 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))Everything else is truthy:
print(bool([1]))
print(bool("a"))
print(bool(42))Which means you check for an empty list directly, not by its length:
items = []
if not items:
print("nothing to do")