Python Syntax
Tutorial 3 of 65 · pythondeck.com Python course
Python uses indentation (typically 4 spaces) to define blocks instead of braces. Statements normally end at the newline; a backslash \ or open bracket lets you continue on the next line. Identifiers are case sensitive. Comments start with #; docstrings are triple-quoted strings placed at the top of modules, classes and functions.
Syntax is the set of rules the parser enforces before your program runs. Python prioritizes human-readable layout: colons introduce blocks, indentation expresses nesting, and punctuation is minimal compared to C-style languages.
A SyntaxError means the interpreter cannot even build an AST—often a missing colon, parenthesis, or invalid indentation. Fixing syntax is the first gate to executing any logic.
Statements end at newline; use backslash or parentheses to continue across lines.
Blocks follow a header line ending with : (if, for, def, class, with, etc.).
Indentation must be consistent—conventionally four spaces per level, no tabs mixed in.
Expressions vs statements: x = 1 is a statement; 1 + 2 is an expression.
Comments start with #; docstrings are string literals in specific positions, not #.
Identifiers use letters, digits, and underscores; they cannot start with a digit.
Python 3 removed old syntax (print as statement, <> inequality) to simplify teaching. Parentheses for function calls and print() are required.
Line continuation inside brackets ()[]{} is implicit—use this for long calls and collections instead of backslash continuations, which are brittle.
The interpreter reads UTF-8 source by default; save files as UTF-8 and declare encoding only when legacy requirements demand a PEP 263 cookie.
Forgetting the colon after if, def, or class headers.
Using = inside if conditions when you meant ==.
Copy-pasting code from PDFs or web pages that introduce curly quotes or non-breaking spaces.
Relying on significant whitespace but viewing code in an editor that hides trailing spaces.
Configure your editor to show whitespace and insert spaces on Tab.
Run python -m py_compile file.py or your IDE linter before committing.
Wrap long lines at 79–88 characters per PEP 8 for team consistency.
Learn one error message at a time; SyntaxError line numbers point to the parser's confusion, not always the true bug.
Re-read the examples below with these ideas in mind; change variable names and inputs to match your own project.
The program below demonstrates indented blocks. Read the comments on each line, run the code, then change names or values to see how the output shifts.
# Example: Indented blocks
# Run in the REPL or save as a .py file and execute with python.
if 3 > 2:
print("yes")
print("still inside the if")
print("outside")
This sample walks through line continuation in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.
# Example: Line continuation
# Run in the REPL or save as a .py file and execute with python.
total = (1 + 2 +
3 + 4)
print(total)
Here is a hands-on illustration of docstring. Follow the inline comments first; only then execute the snippet and compare the result with what you expected.
# Example: Docstring
# Run in the REPL or save as a .py file and execute with python.
def square(x):
"""Return x squared."""
return x * x
help(square)
The program below demonstrates colon blocks. Read the comments on each line, run the code, then change names or values to see how the output shifts.
# Every block header ends with a colon and an indented body
score = 88 # sample numeric value for branching demo
if score >= 90: # condition evaluated once per if statement
grade = "A" # four-space indent marks block membership
elif score >= 80: # elif chains additional tests
grade = "B" # only runs when earlier branches failed
else: # catches all remaining cases
grade = "C" # default letter when thresholds not met
print(grade) # prints outside the if because dedented
for ch in "abc": # for also requires a colon + indent
print(ch.upper(), end=" ") # end keeps output on one line
print() # newline after the loop finishes
This sample walks through implicit continuation in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.
# Parentheses let you break long expressions without backslashes
values = ( # opening paren starts an implicit continuation
10, # first literal
20, # second literal
30, # third literal
40, # fourth literal
) # closing paren ends the tuple literal
total = ( # another multi-line expression
values[0]
+ values[1]
+ values[2]
+ values[3]
) # sum computed after all lines are read
print(total) # expect 100
def area(w, h): # function header also allows split parameters
return w * h # single-line body still needs indentation
print(area(3, 4)) # 12