Course 4.1Lesson 1 of 5
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.
Try the code and the simulations beside the lesson.
After this lesson you can
for loop that repeats lines a number of times,You want to print the message Good morning five times. You could write five print() lines. But what about a thousand times? Nobody wants to type a thousand lines. This is where a loop helps. A loop is a way to say: do this, again and again.
Python's most common loop is the for loop. It repeats some lines once for every value in a row of values.
Look at the first loop, for i in range(3):.
for starts the loop. The line ends with a colon, just like if.i is the loop variable. It is a name that you choose. In each round it holds the next value of the row. The row here is 0, then 1, then 2.range(3) makes the row of values. We study it in the next lesson.print("---"), which runs only once.So the first loop prints Round 0, Round 1 and Round 2. It is three rounds, and the loop variable holds 0, 1 and 2.
The body is every line that is indented under the for.
What if you forget the indent?
The loop variable starts at 0, so in round 1 it is 0 and in the last round it is one less than n.
A for loop can take a text instead of a number row. In each round, the loop variable holds the next letter. Look at the second loop of the first program: for letter in "python": shows p, then y, then t, and so on.
The words after in can be anything that has a sequence of items: a text, a row of numbers, or (in Chapter 11) a list. The loop does the same thing for all of them: one round for every item, in order.
The loop variable is an ordinary variable. Python gives it the next value at the start of each round. You can use it in the body, as in number * 2. After the loop, it still holds the last value. You can choose a good name: i for a counter, letter for letters, number for numbers. A good name makes the loop easy to read.
for line.i outside a loop before it has any value (a NameError).Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
for loop repeats its indented lines, once for every value of the row.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
for i in range(4): print("Hi") show Hi?for letter in "cat": print(letter) show?for is not indented?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.