๐Ÿ”€if / elif / else & Ternary ExpressionsLESSON

if / elif / else & Ternary Expressions

Control flow is how your program makes decisions. Python's if statement evaluates conditions and runs different code blocks depending on the result.

Basic if / elif / else

Key syntax rules:

  • The condition is followed by a colon :
  • The body is indented (4 spaces by convention)
  • elif is short for "else if" โ€” you can have any number of them
  • else is optional and catches everything else
  • Only the first matching branch runs

Indentation Rules

Python uses indentation to define blocks. This is not cosmetic โ€” it is the syntax:

Truthiness: Truthy and Falsy Values

Python's if doesn't require an explicit boolean โ€” it evaluates the truthiness of any value:

Ternary Expressions (Conditional Expressions)

Python's ternary operator lets you write a simple if/else on a single line:

Nested if Statements

Deep nesting makes code hard to read. Prefer early returns to flatten logic:

Chained Comparisons

Python lets you chain comparisons naturally:

Checking Multiple Conditions

Common Patterns

Knowledge Check

Which of the following values is TRUTHY in Python?

What is the correct syntax for a ternary expression in Python?

How many elif clauses can an if statement have?