1 Python Syntax and Program Structure
A progressive guide to Python’s source structure, syntax, values, operators, input and output, execution models, and common errors.
The Building Blocks of a Python Program
Python programs are built from two fundamental kinds of source elements. A performs an action, while an produces a value. For example, an assignment can bind a name to the value produced by an .
A Python source file is a module. A practical organization is:
An optional module
Import statements
Constants and configuration values
Function and class definitions
Code that starts the program
Names refer to objects within namespaces. Assignments, imports, and definitions bind names to objects; assignment does not necessarily copy an object.
A useful structure places reusable behavior in functions and keeps program-starting behavior in main(). The condition if __name__ == "__main__": then calls main() only when the file is run directly, not when it is imported.
Takeaway: Identify whether a piece of code produces a value, performs an action, defines a reusable object, or starts program execution.
Lines, Statements, Comments, and Documentation
Python normally treats the end of a logical line as the end of a . A can continue across physical lines inside parentheses, brackets, or braces. Grouping punctuation is usually clearer than using an explicit backslash for continuation. Multiple simple statements can be separated by semicolons, but separate lines are generally easier to read.
A comment begins with # outside a string and continues to the end of the physical line. Comments should explain intent, assumptions, or non-obvious decisions rather than merely repeat the code.
A is different from an ordinary comment: when a string is the first in a module, function, or class, Python associates it with that object as documentation. It is available through the object’s __doc__ attribute. Python source uses UTF-8 by default; an encoding declaration, when necessary, may appear in a comment on the first or second line of a file.
Takeaway: Use line structure, comments, and docstrings to make the purpose and organization of code visible.
and Block Structure
Python uses to define a instead of braces. A compound has a header ending in a colon, followed by an indented suite. For example, an if header can be followed by an indented print("Freezing") , while an else header introduces a different indented suite.
All statements in the same block must use consistent . Four spaces per level is the conventional style. Mixing tabs and spaces can cause an IndentationError or TabError.
Nested blocks receive additional . Headers such as if, elif, and else align with one another, while the statements controlled by each header are indented beneath it. This alignment also determines which else belongs to which if.
An empty block is invalid. Use pass when a block must exist but has no implementation yet, as in if not implemented_yet: pass.
Takeaway: A colon begins a suite, and consistent determines the structure Python executes.
Names, Literals, and Values
A name identifies an object. Names may contain letters, digits, and underscores, but they cannot begin with a digit. Python is case-sensitive, so count and Count are different names.
Common naming conventions include:
lowercase_with_underscoresfor variables and functionsCapitalizedWordsfor classesUPPER_CASEfor constantsA leading underscore for names intended for internal use
A is source-code notation for a value. Common forms include integers, floating-point numbers, complex numbers, strings, bytes, Boolean values, None, lists, tuples, sets, and dictionaries.
Strings may use single, double, or triple quotes. Triple-quoted strings can span multiple lines. Prefixes add behavior: r creates a raw string, b creates bytes, and f creates a formatted string. An f-string evaluates expressions inside braces when the string is created.
Multiple assignment can bind several names at once, and it can swap references without requiring a temporary name. For example, x, y = 10, 20 followed by x, y = y, x exchanges the references.
Takeaway: Names refer to objects, while literals provide direct notation for values; clear naming conventions make those relationships easier to understand.
Expressions and Operators
An combines values, names, function calls, attributes, indexing, and operators to produce a result. Parentheses make grouping explicit and can override normal precedence.
Arithmetic operators include addition, subtraction, multiplication, true division, floor division, remainder, and exponentiation. Comparison operators produce Boolean results. Python also provides and, or, and not for combining or reversing truth values.
The operators and and or use . For example, supplied_name or "Guest" uses the supplied name when it is truthy and otherwise produces "Guest". These operators return one of their operands, not necessarily the Boolean objects True or False.
Python supports chained comparisons such as 0 <= score <= 100, which expresses a range check compactly. Assignment operators include = and augmented forms such as += and *=. The := assigns a value within an and is best used only when it improves clarity, as in if (length := len(items)) > 0:.
Other important operators and forms include membership testing with in, identity testing with is and is not, attribute access with ., indexing with [], and function calls with ().
Takeaway: Expressions calculate values, and deliberate grouping plus clear operator use prevents precedence and truth-value mistakes.
Input and Output
The print() function converts objects to text and writes them to a text stream, normally the screen. Its sep argument controls the separator between multiple objects, while end replaces the default newline. Formatted strings are useful when text must include values with a particular format.
The input() function displays an optional prompt, reads one line, removes the trailing newline, and returns a string. Convert that string when a numeric value is required; for example, quantity = int(input("Quantity: ")) and price = float(input("Price: ")) use integer and floating-point conversion.
Conversion can fail when the input does not have the expected format, so robust programs validate input or handle the possible exception. The function also raises EOFError when the input stream ends.
Takeaway: Output is written with print(), while input() always begins with text and may require explicit conversion.
How Python Code Executes
Python code can run in an interactive interpreter, as a script, or as an imported module.
In the interactive interpreter, expressions and statements are entered at a prompt for immediate experimentation. The prompts >>> and ... are interpreter indicators, not part of the Python code.
A script is executed by passing its file to the Python interpreter. Python reads, tokenizes, and parses the source before executing valid code. A syntax error prevents invalid code from executing; a runtime error occurs while otherwise valid code is running.
When a module is imported, its top-level statements execute for that import operation, and other code can use the resulting module object. For example, a module may define circle_area(radius) and another file may call it through geometry.circle_area(2). Keeping program-starting code inside main() and guarding it with if __name__ == "__main__": prevents that code from running unintentionally during import.
Python source is parsed and compiled into an internal representation before execution. Implementations may cache compiled bytecode, commonly in __pycache__, but programmers generally work with the source-level model: statements run in order, control flow selects or repeats blocks, and function bodies run when their functions are called. The exact compilation and runtime details can vary among Python implementations.
Takeaway: The same Python file can support experimentation, direct execution, and reuse through imports when its top-level structure is designed carefully.
Avoiding Common Syntax Errors
Syntax errors mean that source code does not follow Python’s grammar. Common causes include a missing colon after a compound- header, inconsistent , unmatched quotes or parentheses, and confusing = with ==. For example, if score > 90 is invalid without a colon; the corrected header is if score > 90: followed by an indented suite.
Other frequent mistakes include using a name before assigning it and forgetting that input() returns text. Readable structure helps prevent these problems: use meaningful names, keep related statements together, indent consistently, prefer clear expressions over clever ones, and separate reusable operations into functions.
A useful debugging distinction is:
A syntax error is detected before the invalid code can execute.
A runtime error occurs while valid code is executing.
Takeaway: Clear layout and a precise understanding of Python’s syntax rules prevent many early errors before execution begins.