liveBook · Manning

Indentation

As explained in Learn AI-Assisted Python Programming, Second Edition

Indentation is leading whitespace or spacing that positions content relative to its surrounding area and can represent hierarchy or structural nesting.

Indentation is leading whitespace that Python uses to determine which lines of code belong together. It is required inside functions, if statements, and for or while loops; incorrect indentation changes the program’s behavior or causes an error. section 5.1.2

Conditionals and nested blocks

In an hour-based greeting, the morning and afternoon messages belong to their conditional branches. The evening message must be indented under else; otherwise, it prints for every hour. A loop nested inside a function requires another indentation level. section 5.1.2

hour = int(input('Please enter the current hour from 0 to 23: '))

if hour < 12:
    print('Good morning!')
    print('Have a nice day.')
elif hour < 18:
    print('Good afternoon!')
else:
    print('Good evening!')
print('Have a good night.')     #1

Inspect the greeting code and identify why the final message executes regardless of the entered hour. section 5.1.2

How Learn AI-Assisted Python Programming, Second Edition covers it

How deep it goes
Explains nested indentation levels and a behavioral error, without descending into interpreter internals.
Examples
Uses an hour-based greeting, larger-value function, word-scoring function, password checker, and nested country loops.
What it assumes
Assumes basic familiarity with Python functions, variables, conditionals, strings, and lists while teaching indentation explicitly.
What you can do after
Diagnose/debug with it: identify misplaced Python statements and adjust indentation to preserve intended control-flow blocks.
How it connects
Connects indentation with functions, if statements, for loops, while loops, and code blocks.

Also explained in

Compare how 6 books explain indentation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn AI-Assisted Python Programming, Second Edition. The section links point to the parts of the book it draws on.