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. What usually goes wrong. What you see What caused it How to fix it --- --- --- The last number is missing from the output range stops one short of the number you hand it Raise the stopping value by one so the final number is included The output starts at 0 instead of 1 range gi

Challenge: Count Up to N