1.4 Basic Syntax and Comments

1.4 Basic Syntax and Comments

We understand the two most fundamental rules of Python: indentation, which structures the code, and the use of comments for documentation.

Python is widely recognized for its clean, elegant, and readable syntax. Two of the most basic syntax elements you need to understand from the start are indentation and comments.

Indentation: The Python Rule

In many other programming languages, code blocks are delimited by symbols like curly braces {}. In Python, indentation (the spaces or tabs at the beginning of a line) is mandatory and defines the code structure. The established convention is to use 4 spaces for each level of indentation.
An indentation error will cause an `IndentationError`, one of the most common errors for beginners.
# Example of correct indentation
if 5 > 2: # The 'if' condition
    # This line is indented by 4 spaces and belongs to the 'if' block
    print("5 is greater than 2.")
    # This line also belongs to the same block, with the same indentation
    print("The condition is true.")

# This line is not indented and runs independently
print("The check is complete.")

Comments: Explaining Your Code

Comments are lines of text that are ignored by the interpreter. They are used to explain the code. A single-line comment starts with the # symbol.
# This is a full-line comment.
print("I am learning Python!") # This is a comment after the code.
For multi-line comments or documentation (docstrings), triple quotes (''' or """) are used.
"""
This is a docstring.
It is used for documenting functions, classes, and modules.
"""
def my_function():
    """This is the docstring for the my_function function."""
    print("This function is executing.")

my_function()
print(f"\nFunction docstring: {my_function.__doc__}")

Statements and Expressions

A Statement is an instruction that performs an action (e.g., `x = 10`). An Expression is a piece of code that produces a value (e.g., `10 + 5`).

Keywords

Python has reserved words (keywords) with special meaning, such as `if`, `for`, `def`, `class`, etc., which cannot be used as variable names.
# You can see all the keywords:
import keyword
print("All Python keywords:")
print(keyword.kwlist)

Practical Exercises

Explore More with AI

Use AI to generate new examples, delve deeper into theory, or get your questions answered.