📝

Python If Statements Overview

Oct 2, 2025,

Overview

This lecture covers the structure and usage of if statements in Python, emphasizing the role of indentation, code blocks, and code readability.

Basic If Statements

  • An if statement is a conditional that runs a block of code only if a specified condition is true.
  • The generic structure is: if condition:, followed by an indented block.
  • The condition is evaluated directly; do not write if x < 10 == True, just use if x < 10.

Execution Flow and Flowcharts

  • If the condition is true, the indented code block runs; if false, the block is skipped.
  • After the if block (regardless of condition), the program continues with the next unindented line.
  • Flowcharts follow true/false paths based on the condition, always leading to the program end.

Indentation and Code Blocks

  • Indentation (4 spaces in Python) defines which lines belong to the if block.
  • Multiple lines can be grouped into a block using the same indentation.
  • Once indentation returns to the previous level, the block ends.
  • Indents can be nested for deeper structures, like if statements inside if statements.

Nested Blocks

  • You can nest blocks by placing an if (or loop) inside another block, increasing indentation.
  • Skipping an outer if block due to a false condition also skips all nested blocks inside it.
  • Indentation levels signal block beginnings and endings.

Style and Readability

  • Avoid blank lines directly after the start of an if block.
  • Vertical spaces within blocks are okay to separate code logically.
  • Clean and consistent indentation makes code readable and easy to follow.
  • Using editors (like Spyder) can help visualize and collapse code blocks.

Practical Examples

  • Blocks can contain any number of lines, including nested if statements.
  • Ending multiple blocks at once is possible by reducing indentation back to the prior level.
  • Excessive nesting is allowed, but deep nesting can make code hard to read and maintain.

Key Terms & Definitions

  • If Statement — A programming construct that runs code conditionally based on whether an expression is true.
  • Condition — An expression evaluated as true or false to control if block execution.
  • Block of Code — One or more lines grouped by indentation that are executed together.
  • Indentation — Spaces at the start of a line used in Python to define code blocks.

Action Items / Next Steps

  • Practice writing if statements with single and multiple-line blocks.
  • Experiment with nested if statements and observe how indentation affects execution.
  • Review code style guidelines for indentation and block separation.