Lesson · Language Fundamentals
Syntax & Code Structure
54 min readSyntax & Code Structure
Python uses indentation and a small set of structural rules to make blocks and expressions readable. Good structure is both a syntax requirement and a maintenance tool.
Learning goals
- Explain how indentation defines blocks, point at the lines a given block owns, and fix an
IndentationError. - Tell statements and expressions apart, and say which can appear inside the other.
- Break a long expression across lines with brackets, and name the case where a backslash is still required.
- Apply PEP 8's naming basics:
snake_casefor functions and variables,PascalCasefor classes, and a single leading underscore for non-public names. - Check whether a word is reserved with
keyword.kwlist, and write a docstring where it actually takes effect.
Mental model
Structure in Python is spatial: indentation groups statements into blocks, and the layout of lines decides where one logical statement ends. Two classifications run through the whole lesson: a statement performs an action while an expression produces a value, and a line break is either implicit inside brackets or explicit with a backslash.
Core idea
Python has no braces, so structure is carried by whitespace and by the grammar of lines: indentation groups statements into blocks, and a statement ends at the newline unless brackets or a backslash say otherwise. The classification to keep beside it is expression versus statement, because only expressions produce values.
Indentation blocks
Indentation is syntactic in Python: it defines suites such as function bodies and loop bodies. Consistent four-space indentation also makes the visual structure match the parser's structure.
Statements vs expressions
An expression produces a value; a statement performs a language-level action such as assignment, import, or control flow. Expressions can appear inside many statements.
Line continuation
Prefer implicit line continuation inside parentheses, brackets, and braces. Backslash continuation exists but is more fragile and usually less readable.
Comments
A comment starts with # outside any string and runs to the end of the line, and the parser discards it. Comments carry no runtime meaning; they exist to explain intent, mark sections, or temporarily disable a line during debugging.
Docstrings preview
A docstring is a string literal placed first in a module, class, function, or method body. Tools expose it through __doc__ and use it for generated documentation and interactive help.
Naming conventions
Python conventions use snake_case for functions and variables, PascalCase for classes, and leading underscores to signal non-public names. Consistency makes APIs easier to scan.
PEP 8 basics
PEP 8 is Python's widely followed style guide: four-space indentation, snake_case for functions and variables, PascalCase for classes, spaces around operators, and blank lines between top-level definitions. The interpreter does not enforce it, but linters and formatters do, and most readers expect it.
Reserved keywords
Keywords are tokens reserved by Python's grammar and cannot be used as ordinary identifiers. The keyword module can report the current interpreter's keyword set.
pass
pass is a statement that does nothing, used where the grammar requires a body but no behavior is wanted yet, such as a stub function or an except block you plan to fill in. It is not a placeholder value: it executes and control moves on.
... / Ellipsis preview
... creates the singleton Ellipsis. It is used by some APIs and type stubs, but it has no special control-flow behavior by itself.
Walkthrough
def classify(value):is a compound statement whose body is defined by indentation: the lines indented one level below it belong to the function, including bothifstatements and the finalreturn.- Each
if value < 0:line ends with a colon and owns the indentedreturnbeneath it;value < 0is an expression producing abool, while the wholeifstatement performs the branch choice. - When
classify(7)runs, both conditions are false and the finalreturn "positive"at function level executes; the returned string is then the argument toprint. - Predict before running: which
returnline runs for7, what changes for-1, and why the lastreturnmust sit at the function's indentation rather than inside anif.
Experiments to try
- Call
classifywith0,-3, and7, and check each path; then putprint("checking")inside the firstifand note when it fires. - Unindent the body of
classifyso thereturnlines line up withdefand read the raisedIndentationError; restore it and retry with a tab in place of four spaces. - Reformat
print(classify(7))across two lines using parentheses, then the same with a backslash; add a trailing space after the backslash and explain theSyntaxError. - Run
import keyword; print(keyword.kwlist)and name three reserved words you have not used yet; then tryclass = 1and read the raisedSyntaxError.
Common mistakes
- Indenting to match what looks right instead of building a block deliberately: an indent wider than the block expects raises
IndentationError, and mixed tabs and spaces in one block raiseTabError. - Writing an expression where a statement is required, or the reverse:
returnoutside a function is aSyntaxError, and a statement cannot be used as a value inside an expression. - Ending a long line with a backslash out of habit: a trailing space after the backslash breaks the continuation invisibly, which is why parentheses are the safer tool.
- Assuming a reserved word can be redefined: names such as
class,def,None, andTrueare parsed as keywords, so using one as an identifier is a syntax error, not a shadowing question.
Practice: Easy
- Type the worked example and call
classifywith7,-1,0, and2.5; record whichreturnline fires for each input. - Remove the colon after
if value == 0and read theSyntaxError; note the line number the parser reports and compare it with the line you edited. - Add a comment inside the function and a docstring right after the
defline; checkclassify.__doc__afterwards and state where the docstring had to sit to appear there.
Practice: Medium
- Rewrite
classifywithif/elif/elseand prove the outputs match the original for the same four calls. - Break
print(classify(7))across two lines with parentheses, then with a backslash; add one trailing space after the backslash and explain theSyntaxError. - Trigger an
IndentationErrortwo ways, an unexpected indent on the first line and a missing body after a colon; match each message to the rule it violates.
Practice: Hard
- Write a program of at least eight statements using
pass, an ellipsis body (...), and a one-lineif; label every line in a comment as statement or expression. - Take a badly formatted snippet of your own and normalize its function and class names to PEP 8; list each rename and the convention behind it.
- Explain why
print(classify(7))is legal butprint(return "positive")is not; separate the roles of statement and expression in the answer.
Lesson checklist
- I can point at a block and say exactly which lines it owns.
- I can classify a line as a statement, an expression, or a statement containing expressions.
- I can continue a long expression with brackets and know when a backslash is still required.
- I can name PEP 8's conventions for functions, classes, and non-public names.
Remember
Python's structure is whitespace plus grammar: blocks are indentation, statements do the work, and expressions supply the values inside them. Prefer parentheses over backslashes when a line grows, follow PEP 8 naming for shared conventions, and keep `pass`, `...`, and keywords for the jobs they are defined to do.
Interview angles
What is the main purpose of **Indentation blocks**?+
Indentation is syntactic in Python: it defines suites such as function bodies and loop bodies. Consistent four-space indentation also makes the visual structure match the parser's structure.
What should you pay attention to when using **Statements vs expressions**?+
An expression produces a value; a statement performs a language-level action such as assignment, import, or control flow. Expressions can appear inside many statements.
How does **Line continuation** fit into this lesson?+
Prefer implicit line continuation inside parentheses, brackets, and braces. Backslash continuation exists but is more fragile and usually less readable.
What breaks if a backslash line continuation is followed by a space?+
The backslash must be the last character on the line to join it with the next one; a trailing space breaks the continuation, so the statement ends and the next line is parsed separately, usually raising a SyntaxError. Wrapping the expression in parentheses avoids the problem.