Practice: break Statement
Q1. Stop at the first negative
Given the list [4, 7, -2, 9, -5], loop through it and print numbers until you meet a negative number. Then stop the loop.
Goal: Use break in a for loop.
Q2. Find the first even number
Loop over [7, 9, 12, 15, 18] and print the first even number, then stop.
Goal: Search with break.
Q3. Count up to a limit
Use a while True loop with a counter starting at 1. Print the counter and break when it passes 5.
Goal: Use while True with break.
Q4. Sum until stop
Read numbers from the list [3, 4, 5, 0, 9] and add them to a total. Stop when you see 0. Print the total.
Goal: Accumulate values and stop early.
Q5. Found or not found
Search the list [2, 4, 6, 8] for the number 5. Use a loop else clause to print Not found when break never runs.
Goal: Use loop else with break.
Q6. First square above 50
Find the smallest positive integer whose square is greater than 50. Print the integer and stop.
Goal: Use break when the stopping point is found inside the loop.
Q7. Break in a for loop
What does this code print?
for i in range(5):
if i == 3:
break
print(i)Goal: Trace a loop with break.
Q8. Code after the loop
What does this code print?
for ch in "python":
if ch == "h":
break
print(ch)Goal: Know the loop variable keeps its last value.
Q9. Nested break
What does this code print?
for a in range(2):
for b in range(3):
if b == 1:
break
print(a, b)Goal: Predict nested loop behaviour.
Q10. Loop else skipped
What does this code print?
for n in [1, 2, 3]:
if n == 2:
break
else:
print("done")
print("end")Goal: Know when loop else runs.
Q11. Loop else runs
What does this code print?
count = 0
while count < 3:
count += 1
if count == 10:
break
else:
print("finished", count)Goal: Combine while and else.
Q12. Break outside a loop
This code gives a SyntaxError. Fix it so it prints Stop when x is negative.
x = -1
if x < 0:
print("Stop")
breakGoal: Spot misuse of break.
Q13. Infinite loop
This loop never stops. Fix it so it prints 1, 2, 3 and then ends.
n = 1
while True:
print(n)
n += 1Goal: Add a reachable exit.
Q14. What does break do?
In one sentence, explain what break does inside a loop.
Goal: Define break.
Q15. Break in nested loops
If break is used in the inner loop of two nested loops, does the outer loop stop?
Goal: Understand break scope.
Q16. Password attempts
A user has up to 3 attempts. The attempts are ["abc", "qwe", "open"] and the secret is "qwe". Print Access granted and stop as soon as the right one is found.
Goal: Apply break to a login-like check.