Python ยท Chapter 12 of 45

Python If / Else

The `if` statement runs a block only when a condition is true. Add `elif` for extra conditions and `else` as a catch-all.

Remember: colon at the end of the line, and indent the body.

Syntax
if condition:
    ...
elif other:
    ...
else:
    ...

Basic structure

if / elif / else evaluates from top to bottom and runs the FIRST true branch.

Ternary expression

`value = a if condition else b` is a compact if/else that produces a value.

Example 1 (python)
age = 18
if age >= 18:
    print("Adult")
else:
    print("Minor")
Output
Adult

The if branch runs because 18 >= 18.

Example 2 (python)
score = 72
grade = "Pass" if score >= 40 else "Fail"
print(grade)
Output
Pass

Ternary expression assigns 'Pass' or 'Fail' in one line.

Key points

  • End the if/elif/else line with a colon.
  • Indent the body (4 spaces).
  • First matching branch wins.
  • Use `elif`, not `else if`.
๐Ÿ’ก Note: Python has no switch/case in older versions; `match` was added in Python 3.10 for pattern matching.

๐Ÿ“ Quick Quiz

1. The keyword for 'else if' in Python is:

2. What follows a condition in an if statement?

3. The ternary expression `a if cond else b` returns: