Python - Syntax & Indentation

Overview

Estimated time: 25–35 minutes

Learn how Python uses indentation to define blocks, how to write statements and expressions, and best practices for readable code.

Learning Objectives

  • Use indentation to structure code blocks correctly.
  • Differentiate expressions vs statements; write simple statements properly.
  • Follow basic style (PEP 8) for consistent, readable code.

Prerequisites

Indentation defines blocks

x = 3
if x > 0:
    print("positive")
    if x > 2:
        print("greater than two")
print("done")

Expected Output:

positive
greater than two
done

Expressions vs statements

# statement:
y = 10
# expression:
result = (y + 5) * 2
print(result)

Expected Output: 30

Common Pitfalls

  • Mixing tabs and spaces. Use 4 spaces per indent; configure your editor.
  • Misaligned blocks cause IndentationError or logic errors.

Checks for Understanding

  1. How many spaces per indentation level are recommended by PEP 8?
  2. What error do you get when indentation is inconsistent?
Show answers
  1. Four spaces.
  2. IndentationError

Exercises

  1. Write a nested if block with two levels and print different messages.
  2. Reformat code that uses tabs into spaces and ensure it still runs.