7. Loops

In this lesson we will go over how to repeat segments of code.

What's iteration?

Iteration is when we tell the computer to repeat code over and over again. There are two main loops in Python, while loops and for loops.

While Loops

While loops are the simpler of the two. How while loops work is there is a condition and when the condition is true, the code repeats. Below is an example of a simple while loop.

i = 0
while i < 10:
    print(i)
    i += 1

Notice how the code under the while loop is indented just like the conditionals were.

Note that 0 to 9 prints and 10 does not get printed, this is because once i was 10, the while loop breaks.

Note if the print(i) and i += 1 were switched, the loop would print out 1 to 10.

If the condition in the while loop is never true, the loop will run forever. Watch out for these forever loops when running code since they never stop.

Just like a conditional statement you can have an while, else statement. The else runs when the while is false. Here is an example:

i = 0
while i < 10:
    print(i)
    i += 1
else:
    print("i is greater than or equal to 10")

For Loops

For loops also repeat code just the while loops but they iterate over a sequence. Below is an example that does the same exact thing as the while loop:

for i in range(0, 10):
    print(i)

Unlike a while loop, the "breaking condition" is harder to notice.

Notice how the for loop does not need to set i = 0, or need the i += 1

Just like the while loop, for loops can have else statements after the loop

Loop Statements

There are two statements that can be used in either a while loop or for loop. They are the break and continue statements.

Break Statement

The break statement is used to "break" out of the loop. When the break statement runs it exits the loop. Here is an example:

i = 0
while i < 10:
    print(i)
    if i == 3:
        break
    i += 1

for i in range(0, 10):
    print(i)
    if i == 3:
        break

Both loops print 0 to 3 and then break or exit the loop.

An else loop will not be executed if a loop is exited by a break statement

Continue Statement

The continue statement is similar to the break statement but instead of exiting the whole loop it stops the current iteration and continues to the next one. Here is an example:

i = 0
while i < 10:
    i += 1
    if i == 3:
        continue
    print(i)

for i in range(0, 10):
    if i == 3:
        continue
    print(i)

Both loops print 0 to 10 but skipped printing the 3.

Nested Loops

You can also have a loop inside of a loop. Just like conditionals, nested loops are indented. Here is an example:

for i in range(0, 10):
    for j in range(0, i):
        print(j, end="")
    print("")
'''
0
01
012
0123
01234
012345
0123456
01234567
012345678
'''

Note how the loop nested uses the variable i as a limit in the range function.

❮ PreviousNext ❯