Python syntax is the set of rules that determines how Python source code is written and understood. Learning those rules is easier when each one is connected to a small program you can run, change, and inspect.
This guide concentrates on stable Python 3 fundamentals: indentation, names and values, built-in collections, control flow, functions, imports, and the difference between code that cannot be parsed and code that fails while running.
Indentation Defines Code Blocks
Python uses indentation to group statements. A block begins after a statement ending in a colon and continues at a consistent indentation level:
temperature = 24
if temperature >= 20:
message = "The room is warm."
else:
message = "The room is cool."
print(message)
Expected output:
The room is warm.
The language uses indentation as syntax, while PEP 8 recommends four spaces for each indentation level. Mixing tabs and spaces in a way that makes indentation ambiguous can raise TabError.
The following example is intentionally invalid because the print statement does not form an indented block:
if True:
print("This line must be indented.")
Expected result: IndentationError, a subclass of SyntaxError.
The lexical analysis reference contains the exact indentation rules.
Names Bind to Objects
Python does not require a type declaration before assigning a name. An assignment binds the name on the left to the object produced on the right. The object has a type; the name can later be rebound to another object:
value = 10
print(type(value).__name__)
value = "ten"
print(type(value).__name__)
Expected output:
int
str
That is more precise than saying Python assigns a permanent type to a variable. Type annotations can document and support tooling, but they do not change this basic name-binding model by themselves.
Strings and Formatted Output
String literals can use single or double quotes. Matching groups of three quotes can contain line breaks, and an f prefix lets expressions appear inside a formatted string:
name = "Alice"
completed_lessons = 3
message = f"{name} completed {completed_lessons} lessons."
print(message)
Expected output:
Alice completed 3 lessons.
The string-literal reference documents quoting, prefixes, and escape sequences.
Lists, Tuples, Dictionaries, and Sets
Python’s built-in collections serve different purposes:
- A
listis an ordered, mutable sequence. - A
tupleis a sequence whose item references cannot be replaced after creation, although a tuple can contain a mutable object. - A
dictmaps unique keys to values and preserves insertion order. - A
setstores distinct hashable values and does not promise a positional order.
colors = ["blue", "green"]
colors.append("gold")
point = (3, 4)
settings = {"theme": "dark", "font_size": 16}
settings["theme"] = "light"
topics = {"python", "syntax", "python"}
print(colors)
print(point)
print(list(settings))
print(settings["theme"])
print(len(topics))
Expected output:
['blue', 'green', 'gold']
(3, 4)
['theme', 'font_size']
light
2
Dictionary insertion order has been guaranteed by the language since Python 3.7. The data structures tutorial explains the collection operations used here.
Conditions and Loops
An if statement selects a block according to a condition. A for loop consumes items from an iterable:
status_code = 204
if 200 <= status_code < 300:
print("The request succeeded.")
else:
print("The request did not succeed.")
topics = ["names", "collections", "functions"]
for position, topic in enumerate(topics, start=1):
print(f"{position}. {topic}")
Expected output:
The request succeeded.
1. names
2. collections
3. functions
A while loop is appropriate when repetition depends on a condition rather than a fixed iterable. Make sure some path through the loop changes that condition so it can eventually stop.
Functions and Docstrings
The def statement creates a function. Its body is indented, parameters receive arguments from the call, and return sends a result back to the caller:
def rectangle_area(width, height):
"""Return the area of a rectangle."""
return width * height
print(rectangle_area(3, 4))
print(rectangle_area.__doc__)
Expected output:
12
Return the area of a rectangle.
The string at the start of the function body is a docstring, not an ordinary comment. Tools can read it through __doc__; the functions tutorial describes the standard docstring conventions.
Importing a Module
A module is a Python file containing definitions and statements. An import statement binds a module name so its public objects can be accessed with attribute syntax:
import math
result = math.sqrt(81)
print(result)
Expected output:
9.0
This example uses the standard library and needs no package installation. The official modules tutorial explains module namespaces, import forms, and the module search path.
Syntax Errors and Runtime Exceptions Are Different
Python must parse a file before it can execute it. A missing colon prevents parsing and produces SyntaxError:
if True
print("This cannot be parsed.")
The next example is valid syntax, but it raises NameError during execution because the referenced name has not been bound:
print(missing_name)
The errors and exceptions tutorial distinguishes parsing errors from exceptions raised while valid syntax is executing. Reading the exception type, traceback, file, and line number is more useful than treating every failure as a syntax problem.
Comments and Readable Style
A comment begins with # outside a string and continues to the end of the physical line. Python ignores comments when parsing the program, but readers still have to maintain them.
Use comments to explain intent, constraints, or a decision that the code does not make obvious. Avoid narrating every assignment. PEP 8’s comment guidance warns that an outdated comment can be worse than no comment.
Readable Python also benefits from meaningful names, focused functions, consistent formatting, and tests that exercise behavior. PEP 8 is a style guide, not a substitute for correct program design or project-specific conventions.
Continue with Classes
Classes add syntax for defining new object types and methods. When you are ready to examine how a class establishes an instance’s initial state, continue with What Does __init__ Do in Python?.
The most useful way to learn these fundamentals is to run each example, change one part, and observe whether the result is a new value, a parsing error, or a runtime exception. That difference is part of understanding the language, not merely memorizing its punctuation.