Brief Overview of Python
The for loop
Use a for loop with range().
Repetition (looping or iteration) runs statements again and again, for example printing attendance for every student in a class. Python's for statement iterates over a range of values or a sequence (numbers, a string, a list or a tuple). The number of repetitions is known in advance.
Syntax: for <control-variable> in <sequence or range>: followed by the indented body of the loop. The body runs once for each item; when the items run out, Python continues with the statements after the loop. The book's Program 3-4 goes through the list [1, 2, ..., 10] and prints each number for which num % 2 == 0, that is, the even numbers.
The range() function: range([start], stop[, step]) produces a sequence of integers from start up to stop, but not including stop, increasing by step.
- If start is left out, it begins at 0; if step is left out, it is 1.
- All arguments must be integers; step can be positive or negative, but never zero.
- list(range(10)) is [0, 1, ..., 9]; list(range(2, 10)) is [2, 3, ..., 9]; list(range(0, 30, 5)) is [0, 5, 10, 15, 20, 25]; list(range(0, -9, -1)) counts down from 0 to -8.
- range() is often used with for; the book's Program 3-5 loops through range(5) and prints num * 10 for num > 0, giving 10, 20, 30, 40.
Nested loops. A loop inside another loop is a nested loop. For each pass of the outer loop, the inner loop runs completely. In the book's Program 3-6, an outer loop of 3 passes and an inner loop of 2 passes print the inner numbers 1 and 2 three times.
Example (new): for table in range(2, 4): followed by an inner for n in range(1, 4): print(table * n) prints 2, 4, 6 and then 3, 6, 9: the inner loop runs all three times for each value of the outer loop.
Practise this lesson
Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.
No account, no email address. Opens the real product.