Python Syntax Fundamentals
Basic Syntax Rules
Python syntax is designed to be simple and readable. Code blocks are defined using indentation (whitespace) rather than braces or keywords.
- **Case Sensitivity**: Python is case-sensitive (`myVar` ≠ `myvar`)
- **Indentation**: Use 4 spaces per indentation level (PEP 8 style guide)
- **Statements**: Typically one per line (no semicolon required)
- **Multi-line Statements**: Continue lines with backslash `\` or by wrapping in parentheses, brackets, or braces
- **Docstrings**: Use triple quotes `"""` for multi-line documentation
Identifiers and Keywords
Identifiers are names for variables, functions, and classes. They must follow these rules:
ℹ️ Note: Python reserves 35 keywords such as `if`, `while`, and `def`, which cannot be used as identifiers.
Valid Examples | Invalid Examples | Reason |
---|---|---|
my_variable | my-variable | Hyphens are not allowed |
_private | 3d_model | Identifiers cannot start with a digit |
MAX_SIZE | for | Keywords cannot be used as identifiers |
x1 | x! | Special characters (except underscore) are not allowed |
Line Structure Example
Example
# Valid multi-line statement using parentheses
total = (item_one +
item_two -
item_three)
# Using backslash for explicit continuation
name = "John " + \
"Doe"
Output
# No output - demonstrates syntax rules
Common Syntax Errors
- **IndentationError**: Inconsistent indentation (mixing tabs and spaces)
- **SyntaxError**: Missing colon `:` after control statements like if or for
- **NameError**: Referring to a variable before assignment
- **TypeError**: Performing operations on incompatible types
⚠️ Warning: Python scripts cannot run with syntax errors. They must be corrected before execution.