JSTAcademy
0 XP
Dashboard
Crash Courses
Control Flow: Making Decisions and Loops
14 min
Basic+160 XP
Crash Courses · Basic

Control Flow: Making Decisions and Loops

Master if/elif/else, while loops, for loops with range(), and build logic that reacts to data.
14 min read+160 XP on completionCert: Python Crash Course
Tap any word in the text below to start reading from there.

Control Flow: Making Decisions and Loops

Comparison Operators

x = 10

print(x == 10)    # True  — equality (two equals signs)
print(x != 5)     # True  — not equal
print(x > 5)      # True  — greater than
print(x < 20)     # True  — less than
print(x >= 10)    # True  — greater than or equal
print(x <= 10)    # True  — less than or equal

# Python supports chained comparisons — unique to Python
age = 25
print(18 <= age < 65)    # True — reads naturally like math
print(0 < x < 100)      # True

---

if / elif / else

score = 78

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"Grade: {grade}")  # Grade: C

# One-line conditional expression (ternary)
status = "pass" if score >= 60 else "fail"
print(f"Status: {status}")  # Status: pass

---

Logical Operators: and, or, not

age = 22
has_id = True
is_vip = False

# and — both must be True
if age >= 21 and has_id:
    print("Access granted")

# or — at least one must be True
if is_vip or age >= 18:
    print("You may enter")

# not — inverts boolean
if not is_vip:
    print("Standard queue")

# Short-circuit evaluation
# "and" stops at first False — B is never evaluated if A is False
# "or" stops at first True — B is never evaluated if A is True
result = has_id and get_user_record()   # get_user_record() only called if has_id is True

# Truthiness — these are all falsy:
# False, 0, 0.0, "", [], {}, set(), None
# Everything else is truthy
name = ""
print("Has name" if name else "No name")   # No name

---

while Loops

# Basic while loop
count = 0
while count < 5:
    print(f"Count: {count}")
    count += 1
# Count: 0, 1, 2, 3, 4

# while with break — search loop pattern
items = [3, 7, 1, 9, 4]
target = 9
i = 0
while i < len(items):
    if items[i] == target:
        print(f"Found {target} at index {i}")
        break
    i += 1
else:
    # This else runs only if the loop completed WITHOUT a break
    print(f"{target} not found")

# Infinite loop with controlled exit
attempts = 0
max_attempts = 3
while True:
    attempts += 1
    success = attempts == 3  # Simulating: succeeds on 3rd try
    if success:
        print(f"Succeeded on attempt {attempts}")
        break
    if attempts >= max_attempts:
        print("Max attempts reached")
        break
    print(f"Attempt {attempts} failed, retrying...")

---

for Loops with range()

# range(stop) — 0 to stop-1
for i in range(5):
    print(i, end=" ")       # 0 1 2 3 4

# range(start, stop)
for i in range(1, 6):
    print(i, end=" ")       # 1 2 3 4 5

# range(start, stop, step)
for i in range(0, 20, 4):
    print(i, end=" ")       # 0 4 8 12 16

# Counting backwards
for i in range(5, 0, -1):
    print(i, end=" ")       # 5 4 3 2 1

# Iterating a string (for loops work on ANY iterable)
for char in "Python":
    print(char, end="-")    # P-y-t-h-o-n-

---

FizzBuzz — Classic Control Flow Test

for n in range(1, 101):
    if n % 15 == 0:        # divisible by both 3 and 5 — check FIRST
        print("FizzBuzz")
    elif n % 3 == 0:
        print("Fizz")
    elif n % 5 == 0:
        print("Buzz")
    else:
        print(n)

The key insight: check the combined case (divisible by 15) first. If you check 3 first, multiples of 15 will print "Fizz" instead of "FizzBuzz".

---

break, continue, and the for/else Pattern

# continue — skip current iteration
for i in range(10):
    if i % 2 == 0:
        continue           # skip even numbers
    print(i, end=" ")      # 1 3 5 7 9

# break — exit the loop entirely
for i in range(10):
    if i == 5:
        break
    print(i, end=" ")      # 0 1 2 3 4

# for/else — else runs only if NO break occurred (prime check)
def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False   # break-like exit via return
    return True            # no divisor found

print([n for n in range(2, 20) if is_prime(n)])
# [2, 3, 5, 7, 11, 13, 17, 19]
0%