Summary
In this lesson, you learned that:
- A loop repeats a block of code. Each run of the block is an iteration. The block is the indented code after the colon, just like with
if. while condition:repeats the block while the condition is true. Something in the loop must change so that the condition becomes false at some point. Otherwise, the loop never ends, and in these exercises, the program is stopped after 5 seconds.for item in items:goes through the elements of a list, or the characters of a text, one by one.range()gives aforloop whole numbers:range(5)is 0 to 4,range(1, 11)is 1 to 10, andrange(0, 21, 5)counts by fives. The stop is never included.- Use
forwhen you know how many times the loop will run, andwhilewhen you don't. - Typical patterns: the sum (a variable that starts at 0 before the loop and adds each value with
+=), the average (the sum divided bylen()), counting (count += 1inside anif), building a new list (.append()inside anif) and the largest value (start with the first element and keep every larger one). - Python's shortcuts
sum(),max()andmin()give the sum, the largest and the smallest value of a list. breakends the whole loop, for example when you have found what you were looking for.continueskips the rest of the current iteration and goes on to the next one.- Loops can be nested: the inner loop runs all the way through in every iteration of the outer one. With
print(..., end=" "), the next output continues on the same line.
Next comes another small project: a report on a week of steps from a fitness band. Then, in the lesson on functions, you will learn to give a piece of code a name and run it whenever you need it, for example a function that works out the average of any list of numbers.
Instructions
- 1
Let's practice with FizzBuzz, a counting game and a classic programming exercise. The players count from 1, but instead of a number divisible by 3, they say
Fizz. With aforloop andrange(), print the numbers from 1 to 15, but printFizzinstead of each number divisible by 3 (that is, whennumber % 3 == 0). The output starts with1,2,Fizz,4. - 2
Now add the full rules: print
Buzzinstead of numbers divisible by 5, andFizzBuzzinstead of numbers divisible by both 3 and 5 (here, that is only 15). Watch the order of your conditions: 15 is also divisible by 3.