Loops are a way to execute code iteratively given a certain condition. The most popular loop in Python is the “For loop”.

For loop

Suppose that you want to sum all integers between 1 and 99. You could do it by hand, but don’t you thing there’s a faster way to do it? With for loops, yes !

total_sum = 0

for i in range(1, 100):
	total_sum = total_sum + i

What does this code do?

We first define a variable which will contain the total sum. We then loop through values between 1 (included) and 100 (excluded) using the keyword range. For each of these values, we add it to the previous sum.

There is also a more concise way to write it when we incrementally change the value of a variable:

total_sum = 0

for i in range(1, 100):
	total_sum += i

The += sign will take the previous value of the variable and add the value of i to it.

There is even a more concise way to write this. The range(1,100) actually creates a list of values. In front of a list, simply use sum to get the overall sum:

sum(range(1,100))

In general, when dealing with loops, look for a way not to write a for-statement since it’s rather slow to execute.

List comprehension

In a for loop, you can decide to append new elements to a list for example based on a condition:

my_list = []

for i in range(1,100):
	if i%10 == 0:
		my_list.append(i)

This will append only multiples of 10 to the list, for all values between 1 and 99 included.

There is a shorter way to write this, and this syntax is called list compregension:

my_list = [i for in range(1,100) if i%10 == 0]

It does exactly the same thing, in 1 line of code instead of 4. You just have to get used to this compact syntax.

While loops

While loops are loops which let you execute a code while a certain condition is met. For example, we can do the exact same operation as before:

total_sum = 0
i = 0

while i < 100:
	total_sum += i
	i += 1

With this while condition, we must increment both the total sum and the index at each step. It is longer to write, and therefore not often used. However, these conditions are useful to test for a True/False condition over which we have less control in for-loops and would require an if-condition in the code:

total_sum = 0
i = 0

while total_sum < 4500:
	total_sum += i
	i += 1

This loop stops turning when total_sum hits 4500 or above.

If you found the article useful or see ways in which it could be improved, please leave a comment :)


Like it? Buy me a coffeeLike it? Buy me a coffee

Categories:

Updated:

Leave a comment