Loops repeat a block of statements. Python has two: while, which repeats as long as a condition holds, and for, which goes through the items of a sequence or other iterable one by one.
The while loop
Syntax
while condition: block
The condition is tested before each iteration; when it is false, the loop ends and execution continues after the loop. The block must eventually make the condition false (usually by changing an iteration variable), otherwise the loop runs forever. while is an indefinite loop: the number of iterations is not known in advance.
The for loop
Syntax
for variable in iterable: block
The variable takes each item of the iterable in turn: the items of a list, tuple or set, the characters of a string, the keys of a dictionary, the lines of a file, or the numbers produced by range(). for is a definite loop: it runs once per item.
range()
range(stop), range(start, stop), range(start, stop, step) produce integers from start (default 0) up to but not includingstop, moving by step (default 1; may be negative but not zero).
Call
Numbers produced
range(5)
0, 1, 2, 3, 4
range(2, 6)
2, 3, 4, 5
range(1, 10, 3)
1, 4, 7
range(10, 0, -2)
10, 8, 6, 4, 2
break, continue and else
Statement
Effect
break
Leave the loop at once; continue after the loop
continue
Skip the rest of this iteration and go to the next one
else on a loop
Runs once when the loop ends normally, not when it ends by break
Key takeaways
while is condition-controlled; for is item-controlled.
range(start, stop, step) excludes stop.
break ends the loop; continue skips to the next iteration.
A loop’s else runs only when the loop was not ended by break.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write a program that reads numbers until the user enters 0 and then prints their sum and count, and say which loop you chose and why.
Show worked answer
total = count = 0, then while True: n = int(input("Number (0 to stop): ")), if n == 0: break, total += n, count += 1, and finally print("Sum:", total, "Count:", count). A while loop is chosen because the number of inputs is not known in advance (an indefinite loop); break ends it when the sentinel value 0 is entered, and 0 itself is not added.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/data-structures-and-control-statements-in-python/loops-while-for-break-and-continue/ to read this page.