A computer does not get tired. A loop lets it repeat the same lines a hundred, a thousand or a million times, while you type them only once. In this course you learn the for loop, the range() function that makes a row of numbers, how a loop builds an answer such as a sum, a count or a factorial, and how to put one loop inside another to make tables and patterns. A project at the end prints a multiplication table book. The practice runs your loops and tells you which results are wrong.
5 lessons, about 2 h 40 min5 simulations14 problems10 practice questionsPython in every lesson
A for loop repeats the lines inside it, once for every value. The line starts with for, names a loop variable, ends with a colon, and the lines under it are indented. The body runs once in each round, and the loop variable holds the next value each time. A for loop can go through a row of numbers made by range() or through the letters of a text. When the values are used up, the program continues with the first line that is not indented.
range() makes a row of numbers. range(n) starts at 0 and stops before n, range(a, b) starts at a and stops before b, and range(a, b, step) goes up in steps. A negative step counts down. The stop value is never included, so range(1, 6) is the way to get 1 to 5. range(a, b) makes b - a numbers. Use list() to see all the numbers at once, and use range() with a for loop to repeat lines a known number of times, or to count up or down.
A loop can build an answer. Make a variable before the loop with the right starting value, change it in every round, and show it after the loop. A total starts at 0 and adds, a product starts at 1 and multiplies, and a counter starts at 0 and adds 1 when a condition is True. If the starting line is inside the loop, the variable starts again in every round, and the answer is wrong. A trace table, with a row for each round, shows what a loop does and finds mistakes. Text can also be built in a loop with stars or letters.
A loop can sit inside another loop. The inner loop runs completely, from start to end, in every round of the outer loop. So an outer loop of 3 rounds and an inner loop of 4 rounds run the body 12 times. Nested loops make tables, grids and patterns. Use print with end to stay on a line, and a plain print after the inner loop to start a new line. Use different names for the two loop variables, and a trace table to follow them.
In this project we print a book of multiplication tables and some patterns. We start from the times table of one number, then a loop around it prints the tables of many numbers, each with a title. We plan the output on paper first, then build it in two steps, test it against the plan, and extend it with a neat grid, a table with a header, and a pyramid. The project uses range(), loops that build text, and loops inside loops.
Log in to join the discussion.
Loading…