Conditions and Loops

Supporting explainer · Computer Science · 1 min read

How if-statements and loops control the flow of a program, with Python examples.

Programs are not limited to running lines in order. Conditions and loops control which instructions run and how often.

Conditions

A condition lets the program choose.

score = 72
if score >= 70:
    print("Pass")
elif score >= 50:
    print("Borderline")
else:
    print("Fail")

This prints Pass because 72 >= 70 is true. The first true branch runs; the others are skipped.

Comparison operators: == (equal), != (not equal), <, >, <=, >=.

Logical operators: and, or, not.

Loops

A loop repeats instructions.

For loop (a known number of repetitions):

for i in range(3):
    print(i)

This prints 0, 1, 2. range(3) produces 0, 1 and 2.

While loop (repeat while a condition is true):

count = 3
while count > 0:
    print(count)
    count = count - 1

This prints 3, 2, 1.

Avoiding infinite loops

If the condition never becomes false, the loop never ends. In the example above, forgetting count = count - 1 would make the loop run forever.

Worked example: sum of 1 to 5

total = 0
for n in range(1, 6):
    total = total + n
print(total)  # 15

range(1, 6) gives 1, 2, 3, 4, 5. The sum is 15.

Common mistakes

Quick recap

Conditions choose a path. Loops repeat steps. Make sure each loop has a way to finish.

Key vocabulary

Keep learning

More: Computer Science hub · Computer Science practice questions