PYTHON PROGRAMMING ยท 12 MIN READ

Python programs and indentation

Python runs statements in order, and leading whitespace tells it which statements belong to the same block.

Learning objectives

  • Run a simple Python statement mentally.
  • Explain why indentation changes Python program structure.

Your first statement

PYTHON
print("Hello, learner!")

print is a built-in function that writes a representation of its arguments to standard output. A string literal is text between matching quotes.

Expected output Hello, learner!

Indentation is syntax

After a compound statement such as if or def, Python uses an indented suite as its body. Consistent four-space indentation is the usual style.

PYTHON
temperature = 31
if temperature > 30:
    print("Carry water")
print("Done")

The first print belongs to the condition. The final print is not indented, so it runs after the conditional whether or not the condition is true.

Common mistakes

  • Mixing tabs and spaces can make a block hard to read or invalid.
  • A colon after if, for, while, and def begins an indented suite.

Summary and references

Python optimizes for readable structure. The next lesson explains how names refer to values.