Index
Python is known for its clean and readable syntax, which makes it an excellent choice for beginners and experienced developers alike. This guide will walk you through the fundamental syntax rules and concepts in Python.
1. Indentation
Indentation is a fundamental aspect of Python syntax. Unlike many other programming languages that use braces {}
to define blocks of code, Python uses indentation to group statements. This makes Python code visually clean and easy to read, but it also means you must be careful with spacing and tabs.
if 7 > 2:
print("Seven is greater than two!") # Indented block
Why Indentation Matters in Python
- Defines Code Blocks: Indentation is used to indicate the body of loops, conditionals, functions, and classes.
- Readability: Proper indentation makes code easier to read and understand.
- Syntax Requirement: Incorrect indentation will result in an
IndentationError
and cause your code to fail.
Basic Rules of Indentation
- Use Consistent Indentation: Always use the same number of spaces or tabs for indentation. The Python style guide (PEP 8) recommends 4 spaces per indentation level.
- Avoid Mixing Tabs and Spaces: Mixing tabs and spaces can lead to errors. Stick to one method (preferably spaces).
- Indent After Colons: After a colon (
:
), the next line must be indented to indicate the start of a block.
Note: Incorrect indentation will result in an IndentationError
.
2. Comments
Comments are used to explain code and are ignored by the Python interpreter.
- Single-line comments start with
#
. - Multi-line comments are enclosed in triple quotes (
"""
or'''
).
Example:
# This is a single-line comment
"""
This is a
multi-line comment
"""