Unit 1 • Lesson 4

Python Syntax and Indentation

Overview

Python uses indentation, not braces or keywords, to define code blocks. In this lesson, you'll understand how proper indentation affects program logic and learn common formatting conventions for writing clean, readable code.

Beginner 15–20 min

What You Will Learn in This Lesson

By the end of this lesson, you will know:

  • What syntax means in programming: Understanding the rules that Python follows when reading your code.
  • How Python uses indentation: Learn why Python uses spaces instead of braces like other languages.
  • Common syntax rules: Master the basic rules like using colons, proper spacing, and correct punctuation.
  • How to fix indentation errors: Understand and fix the most common error beginners encounter.

Why This Matters

Syntax and indentation are fundamental to Python. Getting these right from the start will save you hours of debugging later. Python is strict about indentation, but once you understand it, your code will be cleaner and easier to read.

Step 1: What Is Syntax?

Syntax is the set of rules that define how you write code in a programming language. Just like English has grammar rules (like using periods at the end of sentences), Python has syntax rules that tell the computer how to understand your code.

Correct Syntax

When you follow Python's rules, your code runs successfully. Python understands what you want it to do.

print("Hello")
x = 5

Incorrect Syntax

When you break the rules, Python shows an error. It can't understand what you're trying to do.

print("Hello"  # Missing closing parenthesis
x = 5  # This is fine

Think of syntax like a recipe: If you follow the recipe exactly, you get a delicious cake. If you skip steps or use wrong measurements, the cake fails. Python syntax works the same way. Follow the rules, and your code works. Break them, and you get errors.

Step 2: Python's Unique Approach: Indentation

Most programming languages use curly braces {} or keywords like begin and end to show where code blocks start and end. Python is different. Python uses indentation (spaces at the beginning of lines) to organize code.

Other Languages (JavaScript, Java, C++)
if (x > 5) {
    print("Big number");
    print("Very big!");
}
Python
if x > 5:
    print("Big number")
    print("Very big!")

Notice the difference. In Python, there are no curly braces. Instead, the indented lines (the ones with spaces at the beginning) show what belongs inside the if statement. The indentation tells Python "these lines are part of the same block of code."

Why Indentation?

Python's creator, Guido van Rossum, wanted Python code to be readable. By forcing indentation, Python ensures that code that looks organized actually is organized. This makes Python code easier to read and understand, even for beginners.

Step 3: How Indentation Works

Indentation in Python uses spaces (or tabs, but spaces are recommended). The standard is to use 4 spaces for each level of indentation. Let's see how this works:

Example: Indentation Levels
print("Start")           # No indentation (level 0)
if True:                 # No indentation (level 0)
    print("Inside if")   # 4 spaces (level 1)
    if True:             # 4 spaces (level 1)
        print("Nested")  # 8 spaces (level 2)
print("End")             # No indentation (level 0)
1

Level 0: No Indentation

Code at the leftmost edge (no spaces) runs first and is the main part of your program.

2

Level 1: 4 Spaces

Code indented with 4 spaces belongs to the statement above it (like an if statement).

3

Level 2: 8 Spaces

Code indented with 8 spaces belongs to the level 1 block. This creates nested structures.

Important Rule: All lines at the same indentation level belong to the same block. When you reduce indentation (move back to the left), you're ending that block. Python is very strict about this. Mixing spaces and tabs, or using inconsistent indentation, will cause errors.

Mini Practice #1: Understanding Indentation

Try It Yourself

Look at this code. Can you predict what will be printed? Notice how the indentation groups the code:

Press Run to see output

What happened? The code printed "Start", then "Inside if" and "Still inside" (because they're indented under the if), then "End". The indentation shows Python which lines belong together.

Step 4: Common Syntax Rules

Python has several important syntax rules. Learning these will help you write correct code from the start:

1

Use Colons After Statements

When you write statements that start a block (like if, for, def), you must end the line with a colon :.

if x > 5:  # Colon required
    print("Big")
2

Indent After Colons

After a colon, the next line must be indented. This shows Python what code belongs to that statement.

if x > 5:        # Colon here
    print("Big")  # Must be indented
3

Match Opening and Closing

Parentheses, brackets, and quotes must come in pairs. Every opening ( needs a closing ).

print("Hello")  # Correct: quotes match
print("Hello)   # Error: quotes don't match
4

No Semicolons Needed

Unlike some languages, Python doesn't require semicolons at the end of lines. Just press Enter.

print("Hello")  # Correct: no semicolon
print("World")  # Each line is separate

Step 5: Indentation Errors

The most common error beginners encounter is the IndentationError. This happens when Python can't figure out how your code is organized. Let's see common mistakes:

❌ Error: Missing Indentation
if True:
print("This will cause an error")  # Not indented!

Python expects indented code after the colon.

❌ Error: Inconsistent Indentation
if True:
    print("4 spaces")
  print("2 spaces")  # Different amount!

All lines in the same block must use the same indentation.

✅ Correct: Consistent Indentation
if True:
    print("4 spaces")
    print("4 spaces")  # Same amount!

All indented lines use exactly 4 spaces.

How to Fix Indentation Errors

  1. Check your editor settings: Make sure your editor shows spaces (not tabs) and uses 4 spaces per indent.
  2. Count your spaces: All lines in the same block should have the same number of spaces.
  3. Use your editor's help: Most editors (like VS Code) automatically indent when you press Enter after a colon.
  4. Read the error message: Python tells you which line has the problem. Look at that line and the lines around it.

Mini Practice #2: Fix the Indentation

Try It Yourself

This code has an indentation error. Can you fix it? The print statement should be indented to belong to the if statement:

Press Run to see output

Hint: Add 4 spaces before the print statement so it's indented under the if.

Step 6: Best Practices for Indentation

Following these practices will make your code professional and easy to read:

✅ Do: Use 4 Spaces

Python's style guide (PEP 8) recommends 4 spaces per indentation level. This is the standard used by professional Python developers.

if True:
    print("4 spaces")

❌ Don't: Mix Spaces and Tabs

Never mix spaces and tabs in the same file. This causes errors. Choose one and stick with it (spaces are recommended).

if True:
    print("Spaces")
	print("Tab!")  # Don't do this!

VS Code Tip: VS Code automatically uses 4 spaces when you press Tab. You can see if you're using spaces or tabs by looking at the bottom-right corner of VS Code. It should say "Spaces: 4". If it says "Tab Size: 4", click it to convert to spaces.

End-of-Lesson Exercises

Exercise 1: Fix the Syntax Error

This code has a syntax error. Can you fix it? Remember: code after a colon must be indented.

Write your code above and click "Check Answer" to verify it's correct.

Exercise 2: Create Properly Indented Code

Write code that prints "Start", then if a condition is True, prints "Middle" (indented), then prints "End". Use proper indentation.

You'll need an if True: statement with indented code inside it.

Write your code above and click "Check Answer" to verify it's correct.