This tutorial provides a foundational understanding of Python statements, indentation, and comments – crucial elements for writing clean, efficient, and maintainable code.
Table of Contents
Python Statements
In Python, a statement is a single instruction executed by the interpreter. While typically occupying a single line, long statements can span multiple lines using line continuation (backslashes or parentheses
()
). Statements encompass assignments, function calls, loops, and conditional statements.
Examples:
- Assignment:
x = 10
(assigns 10 tox
) - Function Call:
print("Hello!")
- Conditional Statement:
if x > 5: print("x is greater than 5") else: print("x is not greater than 5")
- Loop Statement:
for i in range(5): print(i)
Python Indentation
Unlike languages using curly braces {}
to define code blocks, Python uses indentation. This determines statement grouping within blocks (if
, else
, for
, while
, functions, classes). Consistent indentation is mandatory; inconsistencies cause IndentationError
.
Correct Indentation:
if x > 5:
print("x is greater than 5")
y = x * 2
else:
print("x is not greater than 5")
Incorrect Indentation:
if x > 5:
print("x is greater than 5") # IndentationError
y = x * 2
else:
print("x is not greater than 5") # IndentationError
Use 4 spaces for indentation; avoid tabs.
Python Comments
Comments are explanatory notes ignored by the interpreter. They enhance code readability and understanding. Python offers two types:
- Single-line comments: Begin with
#
. Anything after#
on the same line is a comment. - Multi-line comments (docstrings): Enclosed in triple quotes (
'''
or"""
). Frequently used to document functions, classes, and modules.
Examples:
x = 10 # Single-line comment
'''
This is a
multi-line comment.
'''
def my_function():
"""This is a docstring."""
pass
Effective commenting is crucial for clean, maintainable code. Keep comments concise and relevant; avoid redundant explanations.