Loops: for and while

Part of: Programming Lab: Python for CSP

Repeating Work A loop runs a block of code many times so you do not repeat yourself. Python has two main kinds. A for loop walks through each item in a collection, one at a time. Each time around, p becomes the next item in parts. The line total += int(p) adds that value into a running total. After the last item, the loop ends and you print the sum. A variable that builds up across iterations, like total, is called an accumulator . Counting Loops range(n) gives the numbers 0 up to but not including n, which is handy for repeating something a fixed number of times. This prints 0, then 1, then 2. It stops before 3. while Loops A while loop keeps going as long as a condition stays True. You must change something inside so the condition eventually turns False, or the loop runs forever. This prints 3, 2, 1. Each pass lowers n by one until n 0 becomes False. Forgetting to change n would create an infinite loop. Key takeaways: - A for loop visits each item in a collection. - range(n) counts 0 to n - 1. - An accumulator builds a result across iterations. - A while loop repeats while a condition holds, so you must move it toward False.

Challenge: Count Up to N