Skip to content

D. Indentation


๐ŸŽฏ Learning Goals

By the end of this lesson, you'll be able to:

  • โ—‹ Understand why indentation matters
  • โ—‹ Understand the difference between inside and outside a loop
  • โ—‹ Be able to indent correctly

Core Concepts

What is indentation?

๐Ÿšช Analogy: the loop's room

Indentationmeans putting spaces in front of code. In Python, indentation is the loop's roomIt is!

Inside the room vs. outside the room

for i in range(3):
    print(i)      # Inside the room (repeated)
    print(i * 2)  # Inside the room (repeated)

print("Done!")      # Outside the room (runs only once)
Position Indentation Run
Inside the room O Repeated execution
Outside the room X Runs only once

Indentation rules

  • Usually 4 spaces Or 1 tab Use
  • Colon (:) Indent from the next line
  • The same block is the same depthindent it with

Example Code

from ursina import *

app = Ursina()

for i in range(3):
    # Inside the room: repeated
    Entity(model='cube', position=(i*2, 0, 0))
    print(f"Cube {i} created!")

# Outside the room: runs only once
print("All cubes created!")

app.run()

What Happens

After creating 3 cubes, prints "All cubes created!"


Quiz

Quiz: indentation
How should the code inside a loop be written?
Show Answer

Answer: A) It must be indented

In Python, the code inside a loop must be indented. Without indentation, IndentationErroroccurs!

Indentation practice:

  • Number of indentation spaces: spaces
  • Indented code runs
  • Without indentation only this runs

๐Ÿ”ง Debug Clinic

Problem: IndentationError: expected an indented block

โŒ Wrong Code

for i in range(3):
print(i)  # No indentation!
Cause: indentation is missing

โœ… Correct Code

for i in range(3):
    print(i)  # 4-space indentation!
Fix: Add 4 spaces!


Try Coding It Yourself

Take what you learned with the blocks and write it yourself in Python code!

Indentation practice

The code inside a loop needs to be indented!

Example Answer
for i in range(3):
    print(f'Inside the room: {i}')  # Repeated 3 times

print('Outside the room!')  # Runs only once

Result: '๋ฐฉ ์•ˆ' prints 3 times, '๋ฐฉ ๋ฐ–' prints only once!

Indenting multiple lines

Try putting multiple lines inside the loop!


๐ŸŽฏ Fill-in-the-Blank Mission

Fill in the blanks to complete the code!

Check answers
for i in range(3):
    print(f'Repetition {i}')

print('Done!')
Check answers
for i in range(3):
    print(f'Task {i}')

print('Complete!')

๐Ÿงฉ Key Takeaways

What you learned in this lesson:

Concept Description
Indentation Putting spaces in front of code
Inside the room (indented) Runs repeatedly
Outside the room (not indented) Runs only once
Rules Use 4 spaces or 1 tab

Review Checklist

  • [ ] Can you explain why indentation is needed?
  • [ ] Do you know the difference in how code runs inside vs. outside a loop?
  • [ ] IndentationErrorDo you know how to fix it when it occurs?