Python Syntax and Indentation
Python uses indentation to define blocks. That makes structure visible, but it also means a misplaced space can change program behavior. Keep one consistent indentation level, let branches state their conditions clearly, and prefer a short explicit block over compressed control flow that hides an important case.
Work through the examples in order. Each one has a small, runnable program, a visible output, and one deliberate change to make. Keep the data rule separate from printing or external work so you can explain and test the behavior at every step.
What You Will Build
This page is a focused Python code lab. The sequence starts with a small working form, then adds one rule, one boundary, or one reusable function at a time. Use a local interpreter while reading; an example is complete only after you run it and predict the changed-input result.
Good Python code makes data ownership and failure behavior visible. Validate external input near the boundary, avoid printing private values, and let a caller choose how to present or persist a calculated result.
Example 1: Indent an if block
The indented line belongs to the condition above it. When the condition is false, Python skips that block instead of executing it halfway.
Python
score = 75
if score >= 60:
print("passed")
Expected Result
passed
Try next: Change score to 59 and observe that no line is printed. Then add an else branch deliberately.
Trace the program from its input through the printed result. Change one value before moving forward, then explain why the result changed. That is how short examples become reliable habits rather than copied syntax.
Example 2: Use if and else for two outcomes
A visible else makes the alternative outcome part of the contract. It is better than returning a believable success for every input.
Python
age = 17
if age >= 18:
print("eligible")
else:
print("not eligible")
Expected Result
not eligible
Try next: Test age 18. Boundary values deserve the same attention as normal values.
Trace the program from its input through the printed result. Change one value before moving forward, then explain why the result changed. That is how short examples become reliable habits rather than copied syntax.
Example 3: Indent a function body
Everything indented under def is part of that function. The return statement exits the function with a value for its caller.
Python
def is_even(number: int) -> bool:
return number % 2 == 0
print(is_even(8))
Expected Result
True
Try next: Try 7 and explain the modulo result before running the code.
Trace the program from its input through the printed result. Change one value before moving forward, then explain why the result changed. That is how short examples become reliable habits rather than copied syntax.
Example 4: Use enumerate for index and value
enumerate avoids manually managing a counter. The loop receives both the position and the current value in a readable form.
Python
tasks = ["read", "code", "review"]
for position, task in enumerate(tasks, start=1):
print(f"{position}. {task}")
Expected Result
1. read 2. code 3. review
Try next: Change start to 0 only when a zero-based index is genuinely meaningful to the reader.
Trace the program from its input through the printed result. Change one value before moving forward, then explain why the result changed. That is how short examples become reliable habits rather than copied syntax.
Example 5: Return early for invalid input
An early return keeps the valid path un-nested. Once an invalid value is handled, the remaining lines describe only the normal rule.
Python
def discount(total: int) -> int:
if total < 0:
return 0
return total // 10
print(discount(250))
Expected Result
25
Try next: Decide whether a negative total should return zero in your domain or be rejected with ValueError instead.
Trace the program from its input through the printed result. Change one value before moving forward, then explain why the result changed. That is how short examples become reliable habits rather than copied syntax.
Example 6: Make the input visible
Start by naming the value the next line depends on. This keeps the lesson input explicit before we apply a transformation or call an external boundary. We are applying that habit while revisiting Python Syntax and Indentation.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
Python
lesson = "Python Syntax and Indentation"
print(lesson.upper())Expected Result
PYTHON SYNTAX AND INDENTATION
Try next: Replace the sample value with one from your own notes, predict the result, and then run it.
Example 7: Guard an empty boundary
A small guard makes the allowed and rejected path visible. We want a caller to receive an intentional result instead of discovering an unexplained failure later. We are applying that habit while revisiting Python Syntax and Indentation.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
Python
def accepted(value: str) -> bool:
return bool(value.strip())
print(accepted("Python Syntax and Indentation"))Expected Result
True
Try next: Try an empty value as well as the normal value and describe why the two outcomes differ.
Example 8: Keep the transformation pure
This step returns a value instead of mixing the rule with display or storage work. That separation gives us a small unit we can run, test, and reuse. We are applying that habit while revisiting Python Syntax and Indentation.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
Python
def double(value: int) -> int:
return value * 2
print(double(6))Expected Result
12
Try next: Call the same rule twice with different inputs and confirm that each result depends only on its input.
Example 9: Make a branch deliberate
Use a named branch where the business rule changes. A future reader should be able to point at the condition and state the result for both sides. We are applying that habit while revisiting Python Syntax and Indentation.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
Python
score = 7
result = "ready" if score >= 5 else "review"
print(result)Expected Result
ready
Try next: Change the boundary value by one and explain exactly which branch becomes active.
Example 10: Use a collection without hidden mutation
Collections become safer when we can see which value is read, which value is derived, and whether the original collection remains owned by the caller. We are applying that habit while revisiting Python Syntax and Indentation.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
Python
lessons = ["Python Syntax and Indentation", "boundary"]
print(" | ".join(lessons))Expected Result
Python Syntax and Indentation | boundary
Try next: Add one more item and predict the derived result before executing the code.
Example 11: Return a named outcome
A named outcome is easier to test than an implied side effect. We can now distinguish a successful path from a rejected path without guessing from console noise. We are applying that habit while revisiting Python Syntax and Indentation.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
Python
outcome = {"status": "ready", "lesson": "Python Syntax and Indentation"}
print(outcome["status"])Expected Result
ready
Try next: Rename the outcome in your own words while preserving the same success and failure rule.
Example 12: Trace a small loop
Work through one value at a time. The point is not to memorize syntax; it is to see how the accumulator or output changes after each repeatable step. We are applying that habit while revisiting Python Syntax and Indentation.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
Python
total = 0
for value in [1, 2, 3]:
total += value
print(total)Expected Result
6
Try next: Use a shorter collection first, then add one value and trace the extra iteration aloud.
Example 13: Keep display at the edge
The core rule prepares a value, while the outer line decides how to show it. That keeps the result usable by a UI, test, API, or command-line caller. We are applying that habit while revisiting Python Syntax and Indentation.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
Python
def display(value: str) -> str:
return f"Lesson: {value}"
print(display("Python Syntax and Indentation"))Expected Result
Lesson: Python Syntax and Indentation
Try next: Change only the display text and verify that the underlying rule and result stay unchanged.
Example 14: Test the closest boundary
A useful example includes the nearest boundary, not only the happy path. We are making the behavior inspectable before a real caller relies on it. We are applying that habit while revisiting Python Syntax and Indentation.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
Python
def quantity(value: int) -> int:
if value < 1:
raise ValueError("quantity must be positive")
return value
print(quantity(1))Expected Result
1
Try next: Try the lowest supported value and then one value just outside the accepted range.
Example 15: Write a tiny regression check
A compact assertion turns the lesson into a repeatable promise. It helps us catch a changed rule before a larger program hides the source of the mistake. We are applying that habit while revisiting Python Syntax and Indentation.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
Python
result = "Python Syntax and Indentation".upper()
assert result == "PYTHON SYNTAX AND INDENTATION"
print("contract holds")Expected Result
contract holds
Try next: Deliberately change the expected value once, observe the failed check, and then restore the correct contract.
Practice Checklist
Do not advance after only reading the output. Rebuild the five examples, change one input in each, and write one small version using your own names and values.
- Practice 1: recreate “Indent an if block”, make the suggested change, and state the expected result before running it.
- Practice 2: recreate “Use if and else for two outcomes”, make the suggested change, and state the expected result before running it.
- Practice 3: recreate “Indent a function body”, make the suggested change, and state the expected result before running it.
- Practice 4: recreate “Use enumerate for index and value”, make the suggested change, and state the expected result before running it.
- Practice 5: recreate “Return early for invalid input”, make the suggested change, and state the expected result before running it.
For a stronger check, identify one invalid input and state exactly what a caller should observe. A generic crash, silent fallback, or hidden side effect is not a complete program contract.
Common Mistakes
- Copying a short program without changing an input and therefore never checking whether its rule was understood.
- Using a compact expression where a branch, validation check, or loop would communicate the real behavior more clearly.
- Using print as the only result of reusable logic instead of returning a value a caller can test or display.
- Putting secrets, full request bodies, or private state into output while debugging.
