Loops are an important part of any programming language. They allow us to execute the same block of code over and over again which keeps us from having to copy and paste it.

In this lesson, we'll look at the two main loops in Python, plus a few statements you can use to control the flow while inside loops.

For Loop

A for loop is the loop that gives us the most control. Let's look at one that prints out the numbers between and including 1 to 10:

PYTHON
for i in range(1, 11): print(i)
BASH
1 2 3 4 5 6 7 8 9 10

Here is a for loop iterating over the characters in a string:

PYTHON
for letter in "sabe.io": print(letter)
BASH
s a b e . i o

A cool thing you can do is attach an else keyword to a for loop. This will cause a code block to run after the loop ends:

PYTHON
for i in range(1, 11): print(i) else: print("We are done!")
BASH
1 2 3 4 5 6 7 8 9 10 We are done!

Python makes looping over things very straightforward.

While loop

A while loop is an even simpler loop. A while loop takes a conditional and if that condition is true, it will continue with another loop.

Let's look at looping from 1 to 10 again but this time using a while loop:

PYTHON
count = 1 while count <= 10: print(count) count += 1
BASH
1 2 3 4 5 6 7 8 9 10

First we declare and initialize a variable named count and set its value to 1. At the first pass, 1 is less than 10, so it loops. We print out the number, increment our variable, and repeat. Eventually, 10 is printed, incremented to 11, and the condition is now false, so the loop finishes.

You can also use the else keyword with while loops as well:

PYTHON
count = 1 while count <= 10: print(count) count += 1 else: print("We are done!")
BASH
1 2 3 4 5 6 7 8 9 10 We are done!

Break Statement

The break statement can be used at any point inside a loop to terminate it right away. Here is how we terminate the loop after the number 5 is printed:

PYTHON
for i in range(1, 11): print(i) if (i == 5): break
BASH
1 2 3 4 5

The loop which normally would have continued until the number 10 was printed, stopped at 5 because we used break.

Continue Statement

The continue statement lets you continue on to the next part of the loop without finishing the rest of the code block. It is almost like break except that it doesn't terminate the loop.

Here's how skipping the numbers 3 and 6 looks like:

PYTHON
for i in range(1, 11): if (i == 3 or i == 6): continue print(i)
BASH
1 2 4 5 7 8 9 10

Exactly as we coded it, the numbers 3 and 6 we skipped because we continued on to the next iteration of the loop instead of allow it to print itself.

Next Lesson »
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.