CODE WITH MARTIN

10. Loops


What Are Loops?

Loops are when Python decides to run some lines of code, go back to a starting point and run them again, over and over, in a loop. We can control how many times it loops and stop it looping whenever we wish. A for loop is common to almost every programming language in the world.

They are extremely useful for processing our lists of things. You can build a list in any of the types that hold items and loop through each of the items inside the list. You might then choose to do something with those list items.

A real world example would be a shopping cart on a web-site. When the customer wants to place the order, your software will loop over the items in the customers basket. For each item it finds, it places an order and eventually, sends the customer an email with an order summary.

Let's dive in and see some loops in action.

For Loops

The first loop we are going to look at is called the for loop. It works by looping through items in a list. It starts with using the first item in the list and ends when it's finished with the last item in the list. Here it is:

fruits = ("Apple", "Orange", "Banana")

for fruit in fruits:
    print(fruit)

Let's break this down. Line 1, we have a tuple with 3 items in it. On line 3, we have our for loop statement. It begins with the word 'for', followed by a name 'fruit', the word 'in', then a name of our tuple 'fruits' and finally ends with a colon character ':'.

The word 'fruit' is the name of a variable that Python creates to track the item in the list. Its value is set to each item that is found in the tuple 'fruits'.

Because there are 3 fruits in our tuple, this loop will execute the indented statements immediatly after the for statement (like functions!). The print function on line 4 is the statement that will execute per iteration of the loop. Run the code and you'll see the 3 fruits printed on a new line in the terminal.

Any kind of list can be used in a for loop. This includes lists '[ ]', tuples '( )' sets '{ }' and dictionaries.

Even strings are seen as something that can be 'iterated' over, so Python lets us use them in a for loop. The variable it uses will be set to each character in the string. Example:

name = "Martin"

for x in name:
    print(x)

This is really helpful for when we're inspecting a string in detail. Imagine checking for someones password they use to create an account. You might want to iterate through the password string to check if they used a capital letter aswell as a special character making sure the password is strong.

For loops can loop for a set number of times using the 'range' function. Here's an example:

for x in range(10):
    print(x)

Notice in the output the number starts counting from 0 and ends on 9. Numbers start from 0 in computers, not 1.

You can also use the range function to count between a range of numbers. Here's how:

for x in range(10, 20):
    print(x)

Sometimes when iterating through a list, you want to stop looping early. We can use the 'break' statement to do that:

for x in range(10, 20):
    if x == 15:
        break
    print(x)

And other times, we might want to skip the rest of the for loop statements and start the next iteration. For that, we can use the 'continue' statement:

for x in range(10, 20):
    if x == 15:
        continue
    print(x)

When 'x' is equal to 15, the 'continue' statement on line 3 executes. This tells Python to jump back up to the start of the for loop and continue with the next iteration. This means that the print statement on line 4 doesn't run, but for all other values of x, the print statement outputs 'x' to the terminal.

While Loop

The second loop to know in Python is the 'while' loop. Again, most other languages support this too.

The difference between this and for loops is that the while loop is based on a condition. The for loop simply iterates over a list of things, there is no condition, it starts at the beginning of the list and finishes when it gets to the last item or you break out of the loop.

While loops will check a condition for each iteration and only stop the loop when the condition result is false. Let's see one in action:

x = 0

while x < 10:
    print("Im still in the while loop because x is less than 10.")
    x += 1

print("The while loop has ended.")

You can see the comparison statement right after the keyword 'while' on line 3. Like for loops, the indented statements after the while statement are the statements that are executed as part of the while loop. They are lines 4 and 5 in this example.

This while loop eventually ends because we are always adding 1 to the 'x' variable on line 5. Eventually, the condition checking that x is less than 10 becomes false.

While loops support the use of the 'continue' and 'break' statements. They behave the same as they do in for loops.

It's extremely important to remember that a while loop will run forever if the condition in the while statement is never false. Having an error like this in a live product would be terrible. It would most likely crash the computer that the software is running on depending what statements are happening inside the while loop. Always take care on ensuring the condition can be false when using while loops.

What We Learned