Python Syntax, Statements & Indentation
Python relies heavily on whitespace and simple line breaks to structure code, making it uniquely readable compared to languages that use curly braces {} or semicolons ;.
1. Line Breaks & Statements
In Python, a line break indicates the end of a statement. Semicolons are not required at the end of lines.
# Standard single-line statements
x = 10
y = 20
total = x + y
print(total)
Multi-Line Statements
When a statement is too long to fit on a single line, it can be split across multiple lines using an explicit line continuation character (\) or implicit line continuation inside brackets (), [], or {}.
# Implicit continuation inside parentheses (preferred)
total_cost = (
item_price_1
+ item_price_2
+ item_price_3
)
# Explicit continuation using backslash
long_string = "This is a very long string that spans " \
"across multiple lines using a backslash."
2. Python Indentation
Python uses indentation (leading whitespace) to define code blocks (such as functions, loops, and conditional statements).
- Standard Practice: 4 spaces per indentation level (PEP 8 standard).
- Rule: Do not mix tabs and spaces in the same file.
# Correct indentation
if x > 5:
print("x is greater than 5")
if x > 15:
print("x is also greater than 15")
else:
print("x is 5 or less")
Indentation Errors
Failing to maintain consistent indentation results in an IndentationError.
# Incorrect: Missing indentation inside an 'if' block
if x > 5:
print("This will cause an IndentationError")
# Incorrect: Inconsistent indentation levels within the same block
if x > 5:
print("First line")
print("Second line has an extra space") # IndentationError
3. Structural Syntax Elements
The Pass Statement
Python expects an indented block after statements ending in a colon (:). If a block contains no code yet (such as during drafting), use pass to avoid a syntax error.
def placeholder_function():
pass # Keeps the syntax valid until implementation
if x == 0:
pass
Docstrings & Inline Comments
Comments begin with a # symbol. Multi-line explanations or documentation blocks use triple quotes (""" or ''').
# Single-line comment
"""
This is a multi-line docstring.
It is commonly used at the top of files, modules,
or functions to document what the code does.
"""
def greet(name):
"""Returns a personalized greeting string."""
return f"Hello, {name}!"
4. Summary of Key Rules
| Concept | Syntax Rule | Example |
|---|---|---|
| Statement End | Line break (no semicolon needed) | a = 5 |
| Block Definition | Colon (:) followed by indented lines |
if True: |
| Indentation Standard | Exactly 4 spaces per nesting level | print("Hello") |
| Empty Block | pass keyword |
def my_func(): pass |