Skip to content

Python Syntax

Python Syntax: Indentation and Its Uniqueness

Syntax is the set of rules that defines how a Python program is written. Compared to most languages, Python’s syntax is famously minimal — no braces, no semicolons at the end of lines, no type declarations. This section covers the rules that matter most when you start.

Statements and Lines

A statement is a single instruction Python executes. By default, one statement sits on one line, and the end of the line ends the statement — no semicolon needed.

statements.py
x = 5
y = 10
print(x + y)
statements.py
x = 5
y = 10
print(x + y)

You can place multiple statements on one line with a semicolon, though it is discouraged for readability:

oneline.py
x = 5; y = 10; print(x + y)   # works, but avoid this style
oneline.py
x = 5; y = 10; print(x + y)   # works, but avoid this style

Line Continuation

For a long statement, break it across lines using a backslash \\, or — preferably — wrap it in parentheses ()(), brackets [][], or braces {}{}, inside which Python ignores line breaks:

continuation.py
# Explicit continuation with a backslash
total = 1 + 2 + 3 + \
        4 + 5 + 6
 
# Implicit continuation inside brackets (preferred)
numbers = [
    1, 2, 3,
    4, 5, 6,
]
continuation.py
# Explicit continuation with a backslash
total = 1 + 2 + 3 + \
        4 + 5 + 6
 
# Implicit continuation inside brackets (preferred)
numbers = [
    1, 2, 3,
    4, 5, 6,
]

Code Blocks and the Colon

A block is a group of statements that belong together (the body of an ifif, a loop, a function). In Python, a block is introduced by a colon :: on the previous line and defined by the indentation that follows.

Diagram:

diagram Python block structure mermaid
How a colon and indentation define a block

Indentation in Python

Unlike many other programming languages that use braces {}{} or keywords like beginbegin and endend to define blocks of code, Python relies on indentation to signify the beginning and end of blocks.

Example:

indent.py
# Python code block using indentation
if True:
    print("This is indented.")
    print("So is this.")
else:
    print("This is not indented.")
indent.py
# Python code block using indentation
if True:
    print("This is indented.")
    print("So is this.")
else:
    print("This is not indented.")

In the above example, the lines of code within the ifif and elseelse blocks are indented to indicate the scope of each block. The level of indentation is crucial, as it determines the structure of the code.

Importance of Indentation

The use of indentation in Python is not just a matter of style; it’s a fundamental aspect of the language’s syntax. Indentation helps to improve code readability and enforces a consistent coding style across projects. It also eliminates the need for explicit block delimiters, making Python code cleaner and more concise.

Comparison with Other Languages

Consider a similar example in a language like C++:

indent.cpp
// C++ code block using braces
if (true) {
    cout << "This is enclosed in braces." << endl;
    cout << "So is this." << endl;
} else {
    cout << "This is also enclosed." << endl;
}
indent.cpp
// C++ code block using braces
if (true) {
    cout << "This is enclosed in braces." << endl;
    cout << "So is this." << endl;
} else {
    cout << "This is also enclosed." << endl;
}

In this C++ example, blocks are defined by braces {}{}. The indentation is not significant; it’s purely for human readability.

Tips for Indentation in Python

  1. Consistency is Key: Maintain a consistent level of indentation throughout your code. The standard convention is to use four spaces for each level of indentation.

  2. Whitespace Matters: Be cautious with whitespace. In Python, leading whitespace (spaces or tabs) is considered part of the syntax.

  3. Use an Editor with Indentation Support: Many code editors automatically handle indentation for you. Configure your editor to use spaces or tabs consistently.

Python is Case-Sensitive

Python treats uppercase and lowercase letters as different. NameName, namename, and NAMENAME are three separate identifiers, and keywords must be lowercase (TrueTrue, not truetrue — except the booleans which are capitalised).

case.py
name = "Alice"
Name = "Bob"
print(name)   # Alice
print(Name)   # Bob
case.py
name = "Alice"
Name = "Bob"
print(name)   # Alice
print(Name)   # Bob

Keywords and Identifiers

Keywords are reserved words with special meaning (ifif, forfor, defdef, returnreturn, classclass, …). You cannot use them as variable names. Identifiers are the names you give to variables, functions, and classes; they may contain letters, digits, and underscores, but cannot start with a digit.

keywords.py
import keyword
print(keyword.kwlist)   # prints every reserved keyword
keywords.py
import keyword
print(keyword.kwlist)   # prints every reserved keyword

Output:

command
C:\Users\Your Name> python keywords.py
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', ...]
command
C:\Users\Your Name> python keywords.py
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', ...]

Conclusion

Understanding Python’s indentation syntax is crucial for writing clean and readable code. Embrace the uniqueness of Python’s syntax, and you’ll find that it contributes to the language’s elegance and readability.


Try it: Syntax Exercises

Exercise 1 – Correct Indentation

Exercise 2 – Nested Indentation

Exercise 3 – Loop Indentation

Explore more Python syntax and best practices with our tutorials on Python Central Hub!

If this helped you, consider buying me a coffee ☕

Buy me a coffee

Was this page helpful?

Let us know how we did