Computer Science•Chapter 3•2 min read

Python — Conditions, Loops & Iteration

O
OIYO EditorialContributor
3/8

Conditionals

score = 85

if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
else:
    print("F")
# Output: B

Loops

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

# while loop
count = 0
while count < 3:
    print(f"Count: {count}")
    count += 1

# Iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Iteration and termination boundaries

A range excludes its stop value. A while loop needs an update or exit path to avoid running indefinitely. break exits the innermost loop; continue proceeds to the next iteration. A loop’s else executes after completion without a break, not simply when a Boolean branch is false.

for index, label in enumerate(["A", "B"], start=1):
    print(index, label)

for name, score in zip(["Alice", "Bob"], [90]):
    print(name, score)

for number in [1, 3, 5]:
    if number % 2 == 0:
        print("Found an even number")
        break
else:
    print("No even number")

Output:

1 A
2 B
Alice 90
No even number

Default zip stops at the shortest iterable. Check lengths or use zip(..., strict=True) when unequal lengths indicate invalid data. Removing list items while iterating can skip elements; create a filtered result when preserving the original is intended. In nested loops, identify which loop each break exits. Input retry and cancellation policies are separate from loop syntax.

Chapter 4 Preview

Next: Functions, Modules & Object-Oriented Programming.

O

OIYO Editorial

Editorial Desk

The OIYO editorial desk researches money, law, lifestyle, and self-understanding topics against primary sources and public statistics. Every piece carries source notes and is reviewed on a regular cycle for accuracy and usefulness.