Beginner Python tutorial – 04 – For and While loops

Video version:

Sometimes we need to iterate over a list of items. Or perform the same operation a certain number of times. To do so, we use the For and While loops.

For Loops

When we use for, we pass a list of elements. The for loop iterates over each one of them, and we can perform operations over each element.

Normal For loop

for number in [1, 2, 3, 4, 5, 6]:
    print(number)

On the first iteration, we pass down ‘1’ as ‘number’, and we print that number’s value. Then, we repeat the same operation for 2, 3, 4, 5 and 6, printing each number.

Let’s see another example:

for working_day in ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]:
    print(working_day + ' is a working day')

As you can see, we are not limited to numbers; we can iterate over strings, numbers, other lists and more.

But what if we want to perform the same operation 10 times? We need to write a for loop as “for number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:”? What if we want to repeat it 100 times? 1000?

Range For loop

In Python we can indicate how many times we want to run the same code with range. Just like this:

for number in range(6):
    print(number)

This will print 6 times the value of ‘number’ variable. Beware! That won’t print from 1 to 6, as we start counting by 0 in almost every language, so we’ll get 0, 1, 2, 3, 4 and 5, but no 6.

But not always we need to start our iterations from 0. Sometimes we want to start them from 1, 100 or 53. That’s when we specify not only the stop but also the starting number:

for number in range(5, 15):
  print(number)

This will print all the numbers from 5 up to 15 (not included).

As we can specify the start and the stop, we can indicate the step: How Python will jump from one number to the next. A step of 2, will iterate over half the numbers. A step of 5, every 5 numbers. Let’s see how it works:

for number in range(0, 50, 5):
  print(number)

What do you think it is going to happen here?

It will print the first number, 0, but it will skip 1, 2, 3 and 4, to print 5 as the second number. Again, it skips the next 4 numbers, being 6, 7, 8, and 9, to print 10, and so on.

List comprehension

Note of the writer: This for loop version is a more advanced version of for loops. You don’t need to use it on the first day learning for loops. But you’ll see it in other’s people code, so at least get used to it.

Sometimes we use for loops, not to iterate over a list but to create another one. To do that, we iterate over a for loop and we add each element to the list with append. Let’s see an example:

list_double = [] # With brackets we tell Python that this variable is a list
for x in range(10):
    list_double.append(x * 2)

print(list_double) 

We create list_double, a list, and on each iteration we append two times the number’s value.

We can do that on just one line with list comprehension:

list_comprehension = [x * 2 for x in range(10)]
print(list_comprehension)

As I said at first, this is a bit complex for beginners and it may seem counter-intuitive, but with time you’ll understand it. Simply at the right side we perform the loop, and at the left side we type what we want to append to the list. In this example, we multiply by 2 each number from 0 to 10.

Both loops will print the same value as they are equivalent.

While

Not as usual as for, but sometimes we can use while. In while, we perform the same operation until the condition indicated is broken. As always, it is better to show than to explain:

x = 0
while x < 5:
    print(x)
    x = x + 1

First, we assign 0 to our iterator, ‘x’. Then, we tell to while “Perform the operation indicated below while x is lesser than 5”. After that, we write what we want to do and, and this is important, we add 1 to x.

I say this is important because if we don’t add 1 to x, x value will be 0 always, and it will stuck in the loop forever until we decide to close the program.

If you are curious, remove the last line and run the following code, but be prepared to ALT+F4 your program:

x = 0
while x < 5:
    print(x)

Don’t say I didn’t warned you!

Challenge time

For loops are a building block of Python and one of its most used features. So I prepared a little challenge for you to do.

Don’t worry, it is an easy one. As long as you know how to multiply, of course.

In this exercise, you need to ask the user for a number, then to create a multiplication table with the user’s number.

Resultat d'imatges de multiplication tables

Just like that. Remember that every problem it is easy to solve if you turn it into a collection of small, easy to solve problems.

You just need to ask the user for a number, then use for to print the result of that multiplication.

Ask for a number, use a for loop and print the result.

Try it to solve it on your own. Doesn’t matter if you need 5 or 60 minutes. Re-read this lesson or any past lesson, use Google, etc.

But THIS is how you learn. More than reading and memorizing this post (Hey, but keep reading them!).

Compare your solution with mine at: https://repl.it/@DavidMM1707/04-Looping-time

Video version: https://www.youtube.com/watch?v=kZu-ot9lXvo

Find me on Twitter at: https://twitter.com/DavidMM1707

My GitHub: https://github.com/david1707

Learn more about:
– For and While Loops: https://www.learnpython.org/en/Loops

Fifth lesson: 05 – Basic Arithmetics