- Which loop header makes
i take exactly the values 1, 2, 3, 4, 5? Answer: for i in range(1, 6):
range(start, stop) includes start but excludes stop, so range(1, 6) gives 1 through 5. range(1, 5) is tempting, but it stops before 5 and only gives 1 through 4.
- Inside
for i in range(3):, the body sets i = 10. What happens to i on the next iteration? Answer: It gets the next value from range
A for loop pulls each new value from the iterable, so reassigning i lasts only for that pass. It is not a counter checked against 3, so setting it to 10 does not end the loop; the next pass still gets the next range value.
- What happens when Python runs
for x in 5: print(x)? Answer: It raises a TypeError
A for loop needs an iterable, and an int is not one, so Python raises TypeError: 'int' object is not iterable. It does not act like range(5); you must write range(5) to loop five times.
- What values does
for i in range(10, 0, -3): print(i, end=" ") print? Answer: 10 7 4 1
range(10, 0, -3) starts at 10 and subtracts 3 while the value is still greater than 0: 10, 7, 4, 1. The start value is included, so the sequence does not begin at 7; only the stop value 0 is excluded.
- A
for loop has an else: block attached to it. When does that else block run? Answer: When the loop finishes without a break
A for loop's else runs once after the loop ends normally, meaning no break occurred. It is not limited to empty iterables: a loop that runs every pass without breaking also triggers else, while break skips it.