Python · Syntax: indentation, comments, print
How Python uses indentation instead of braces, how comments work, and the options print() takes.
Python has no { } around blocks. A colon opens a block, and every line in that block is indented by the same amount. PEP 8 recommends 4 spaces. If the indentation is inconsistent you get an IndentationError, so here indentation is syntax, not just style.
Comments start with # and run to the end of the line. A string on its own line (often triple-quoted) is not a comment; it is an expression whose value is thrown away. At the top of a function, though, it becomes the docstring.
print() takes any number of values. It also has keyword arguments:
sep: what goes between values (default is a space)end: what goes after the last value (default is a newline)
# a block is opened by ":" and defined by indentation
x = 7
if x > 5:
print("x is big") # inside the if-block
print("still inside")
print("outside the block")
print("a", "b", "c") # default sep=" "
print("a", "b", "c", sep="-") # custom separator
print("no newline", end=" | ")
print("same line")
Output:
x is big
still inside
outside the block
a b c
a-b-c
no newline | same lineSources
- An Informal Introduction to Python — Python Software Foundation
- Lexical analysis: indentation — Python Software Foundation
- PEP 8: Style Guide for Python Code — Python Software Foundation
- Built-in functions: print — Python Software Foundation