C
Python/Intro/Lesson 05

Control Flow — if · for · while · Comprehension Basics

30 min·theory
This chapter
4/7

Control Flow — if · for · while · Comprehension Basics

🎯 After reading this lesson

Once you finish this lesson, you will be able to confidently do the following 3 things.

  • ✅ Indentation rules (PEP 8 — 4 spaces)
  • ✅ Correct usage of enumerate · zip · range
  • ✅ List comprehension + dict comprehension

Keep the learning objectives as a checklist and close the lesson once you can answer all of them.

if · elif · else — *Conditional Branching + Indentation Rules*

if / elif / else — The basics of conditional branching

python
score = 85

if score >= 90:
    grade = 'A'
elif score >= 80:    # elif (one word) not else if
    grade = 'B'
elif score >= 70:
    grade = 'C'
else:
    grade = 'F'

print(grade)   # 'B'   ← 85 is >= 80, so the second branch

Key rules:

  • A colon : is required at the end of the condition line
  • The next line must be indented by 4 spaces (block)
  • It's elif, not else if — Python's own shorthand

Comparison operators: == (equal) / != (not equal) / >= (greater than or equal) / <= (less than or equal) / < / >


Conditional expression (ternary) — one-line if

python
age = 28
label = 'Adult' if age >= 19 else 'Minor'
print(label)   # 'Adult'

{value1} if {condition} else {value2} — same as JS's cond ? a : b, but the order is different (value comes first).


truthy / falsy — the hidden rule of if

python
if x:            # Is x truthy (considered to "have a value")
if not x:        # Is x falsy

Python's 7 falsy values: 0, 0.0, '', None, False, [], {}, (). Empty collections are also falsy.

python
items = []
if items:                     # False — an empty list is falsy
    print('Exists')
elif items is None:           # Explicit None check (PEP 8: recommends is None over == None)
    print('Uninitialized')
else:
    print('Empty')         # ← This is printed

Indentation rules — the #1 cause of SyntaxErrors

Python uses indentation depth instead of { } to delimit blocks. Lines at the same depth belong to the same block.

python
if x > 0:
    print("Positive")          # 4 spaces indentation → inside if block
    print("Second line")    # Same depth → same block
else:
    print("Negative or zero")

3 common errors

1. IndentationError: expected an indented block

python
if x > 0:
print("Positive")    # ❌ No indentation

→ The line after if must be indented. Use pass for an empty block:

python
if x > 0:
    pass        # ✅

2. IndentationError: unexpected indent

python
print("hello")
    print("world")   # ❌ Sudden indentation (no block-starting keyword)

3. Mixing tabs and spaces — the invisible trap

python
def foo():
    print("a")    # 4 spaces
	print("b")    # Tab → width varies by editor → bug

PEP 8 standard: 4 spaces. Configure your editor to convert Tab → 4 Spaces automatically.

for · while · range · enumerate · zip — *Loops in Full*

Basic for — iterating over an iterable object

python
for name in ['A', 'B', 'C']:
    print(name)

There is no index-based for like Java's for(int i=0; i<n; i++). Use range() to generate indices.

range() — numeric sequences

python
range(5)         # 0, 1, 2, 3, 4
range(2, 8)      # 2, 3, 4, 5, 6, 7
range(0, 10, 2)  # 0, 2, 4, 6, 8 (step)
range(10, 0, -1) # 10, 9, ..., 1 (reverse)

End value is excluded. Same behavior as Java/JS.

python
for i in range(5):
    print(i)     # 0, 1, 2, 3, 4

enumerate() — index + value at the same time

python
names = ['A', 'B', 'C']
for i, name in enumerate(names):
    print(i, name)
# 0 A
# 1 B
# 2 C

for i, name in enumerate(names, start=1):    # Start from 1
    print(f'{i}. {name}')

Use enumerate when you need the index. range(len(arr)) is considered un-Pythonic.

zip() — iterate over multiple sequences simultaneously

python
names = ['A', 'B', 'C']
ages = [30, 25, 28]

for name, age in zip(names, ages):
    print(name, age)
# A 30
# B 25
# C 28

Stops automatically based on the shorter sequence. A pattern for processing corresponding elements from two collections.

while and break · continue

python
n = 0
while n < 10:
    if n == 5:
        break          # Immediately terminate loop
    if n % 2 == 0:
        n += 1
        continue       # To the next iteration
    print(n)
    n += 1

for-else — an unusual syntax

python
for item in items:
    if item == target:
        print('Found')
        break
else:
    print('Not found')    # Runs *if break is not encountered and loop finishes normally*

The else block runs when the loop finishes normally. Useful for search patterns — a Python-exclusive feature not found in other languages.

List Comprehension — *Python's Identity*

Basic form

python
# Existing: for + append
squares = []
for x in range(10):
    squares.append(x ** 2)

# Comprehension
squares = [x ** 2 for x in range(10)]

4 lines → 1 line. More than half of all Python code generated by AI uses this syntax.

Adding a conditional filter

python
even_squares = [x ** 2 for x in range(10) if x % 2 == 0]
# [0, 4, 16, 36, 64]

if at the end — a filter. Equivalent to JS's .filter().map() combined into one line.

Nested comprehensions

python
matrix = [[i * j for j in range(3)] for i in range(3)]
# [[0, 0, 0], [0, 1, 2], [0, 2, 4]]

Multiple fors — the outer for is the outer loop.

Dict comprehension

python
squares = {x: x ** 2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Set comprehension

python
unique_lengths = {len(name) for name in names}
# Deduplicated lengths

Readability limits

python
# ❌ Too complex — rewrite with a regular for loop
result = [
    process(x, y)
    for x in items
    for y in others
    if x.active and y.active and check(x, y)
]

Two or more levels + complex conditions — a regular for loop is easier to read. Comprehensions are powerful only when they're short.

🤖 Try asking AI like this

  • "Convert this for loop into a list comprehension"
  • "Unwrap this enumerate + zip combination in one shot"
  • "Fix this indentation error" (send the whole code along for an instant fix)

🐍 Try It Out — if · for · while · Comprehension

Experiment with all four types of control flow on a single screen. Try changing scores and conditions to see how the output changes.
✏️ Python 코드
📟 Console output
▶ Press the Run button
🐍 Real Python via Pyodide — first run takes 3–5s to load
Read this first: Mastering Lists
Control Flow — if · for · while · Comprehension Basics - Python