Python Syntax and Structure

Indentation defines blocks, statements end at the line break, and a short set of rules about comments, keywords and identifiers covers everything else.

Indentation is the syntax

Most languages mark a block with braces and treat indentation as decoration. Python inverts that: indentation is the block marker and there are no braces. A line ending in a colon opens a block, and every line indented under it belongs to that block.

total = 0

for value in [4, 9, 16]:
    total = total + value      # inside the loop
    print("running", total)    # inside the loop

print("final", total)          # outside the loop

Move that last print four spaces to the right and the program still runs, but it now prints three times instead of once. Indentation changed the meaning, not the appearance.

The rules

  • Use four spaces per level. This is a convention, not a requirement, but it is followed almost universally.
  • Be consistent within a block. Mixing tabs and spaces raises a TabError.
  • Any consistent amount works, but a block cannot be empty. Use pass as a placeholder when you have nothing to put there yet.
def not_written_yet():
    pass
Configure your editor to insert four spaces when you press Tab. Every Python editor has this setting, and turning it on removes an entire category of error permanently.

Statements and lines

A statement ends at the end of the line. No semicolon is needed, and adding one is legal but unidiomatic.

price = 250
quantity = 3
total = price * quantity

Continuing a long line

Two mechanisms exist, and one of them is clearly preferred.

# Implicit continuation: anything inside (), [] or {} may span lines.
totals = [
    120,
    340,
    560,
]

message = (
    "This sentence is long enough "
    "that splitting it across lines "
    "reads better."
)

# Explicit continuation with a backslash. Legal, but fragile.
total = 120 + \
        340

Prefer brackets. A backslash must be the very last character on the line, and a single trailing space after it is an error that is invisible on screen.

Several statements on one line

a = 1; b = 2      # legal, and discouraged

Python allows it. Style guides advise against it, because it hides the second statement from a reader scanning down the left edge.

Comments

# A full line comment explaining why, not what.

rate = 0.18   # an inline comment, two spaces before the hash

# There is no /* block comment */ in Python.
# Comment out several lines by prefixing each one.

A triple quoted string on its own is sometimes used as a multi line comment. It is not a comment; it is a string that is created and discarded. In the first position of a module, function or class it becomes a docstring, which is different and useful:

def net_price(amount, rate):
    """Return amount plus tax at the given rate."""
    return amount * (1 + rate)


print(net_price.__doc__)

Keywords

Keywords are reserved. They cannot be used as names.

False    None     True     and      as       assert   async
await    break    class    continue def      del      elif
else     except   finally  for      from     global   if
import   in       is       lambda   nonlocal not      or
pass     raise    return   try      while    with     yield
import keyword

print(keyword.kwlist)          # the definitive list for your version
print(keyword.iskeyword("in")) # True

Identifiers

An identifier is any name you choose: variables, functions, classes, modules.

  • May contain letters, digits and underscores.
  • May not begin with a digit.
  • Are case sensitive, so total and Total are two different names.
  • May not be a keyword.
order_total = 100     # valid
_internal = 5         # valid, the leading underscore signals "private by convention"
total2 = 7            # valid
# 2total = 7          # SyntaxError: cannot start with a digit
# class = "A"         # SyntaxError: class is a keyword

Naming conventions from PEP 8

PEP 8 is the official style guide. It is not enforced by the interpreter, but following it makes your code look like everybody else's, which is the entire point.

ThingConventionExample
Variable, function, methodlower_case_with_underscoresorder_total, send_invoice()
ConstantUPPER_CASE_WITH_UNDERSCORESMAX_RETRIES
ClassCapWordsInvoiceLine
Module and packageshort lowercaseinvoices, report_utils
Internal by conventionleading underscore_cache

The rest of PEP 8 in brief

  • Four spaces per indent level, never tabs.
  • Keep lines to a readable width; 79 characters is the classic limit and many teams use a larger one, but a limit exists.
  • Two blank lines between top level definitions, one blank line between methods inside a class.
  • Spaces around binary operators and after commas, but not just inside brackets: f(a, b), not f( a,b ).
  • Imports at the top of the file, one per line, standard library first.

Common mistakes

  • Forgetting the colon at the end of an if, for, while, def or class line.
  • Mixing tabs and spaces, usually after pasting code from a web page.
  • Leaving a block empty instead of writing pass.
  • Using a keyword or a built in name as a variable. list = [1, 2] is legal and then list(...) stops working for the rest of the program.
  • Trusting a triple quoted string to be a comment. It is a string, and it is evaluated.

Best practices

  • Let the editor manage indentation, and turn on the display of whitespace.
  • Write comments that explain why. The code already states what it does.
  • Give a name that describes the value, not its type. customers beats customer_list.
  • Adopt PEP 8 from the first file. Retrofitting style to a finished project is far more work.

Practice

  1. Take a loop with a print after it, shift that print into the loop, and describe how the output changes and why.
  2. Rewrite a 120 character expression using bracket continuation rather than a backslash.
  3. List five identifiers that are legal and five that are not, giving the reason for each rejection.
  4. Explain the difference between a comment and a docstring, and demonstrate how to read a docstring at runtime.

Conclusion

Python replaces punctuation with layout. A colon opens a block, indentation defines it, and the line break ends a statement. Combine that with PEP 8 naming and your code will already read the way experienced Python code reads.

Written by Lorens Mishra

Default administrator account created by the installer.

Continue reading

All Python notes →
Python

Introduction to Python

Python is a high level, dynamically typed, interpreted language whose whole design goal is that a program should be as easy to read as it was to write...

Read more

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.