Indentation, Semicolons, and Comments
This section introduces you to how Python structures code. Three key rules shape every Python script: indentation, semicolons, and comments.
Indentation
Python uses indentation (spaces or tabs) instead of curly braces {} to group code blocks. Lines with the same indentation level belong together, while deeper indentation shows nested code.
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is 5 or less")Output
x is greater than 5
Indentation is mandatory in Python, and the interpreter will raise an IndentationError if it is missing or inconsistent. This rule keeps code structured, clean, and easy to read.
Semicolons
Unlike many other languages, Python does not require semicolons at the end of lines. A newline normally ends a simple statement; expressions can continue inside parentheses, brackets or braces. You can use semicolons to write multiple statements on one line, but this is rarely done:
a = 5; b = 10; print(a + b)Output
15
Comments
Comments explain code and are ignored by Python when it runs.
Single-line comments start with #:
# This checks if a number is positive
if x > 0:
print("Positive number")Output
Positive number
For a comment spanning several lines, begin each line with #. Triple quotes (''' or """) create strings, not comments. A string at the beginning of a module, class or function can be a docstring, which documents that unit. The example below is a string expression and prints nothing.
"""
This program compares a number with 5.
It prints whether the number is greater or smaller.
"""Understanding indentation, semicolons, and comments ensures that your Python code is clear, correct, and easy to maintain.