In this tutorial, you’ll learn about loops —a very important concept in programming. In plain English, loops correspond to “Do this action X times.” or “Keep doing that action as long as this condition is true.”
Let’s get started!
Programmers don’t like to repeat themselves. Programming is all about automating things. That’s where loops come in handy.
Let’s start with a list of people:
people = ['Rachel', 'Monica', 'Phoebe', 'Ola', 'You']
We want to greet all of them by their name. But we don’t want to greet every person manually, right?
Let’s look at how we can do this:
To go over the list of people we can use a
for name in people:
name is a variable that temporarily stores the current value of the item in the
people list as we go over all of them one by one. This is also referred to as iterating over a list.
for statement behaves similarly to the
if statement; code below both of these need to be indented four spaces.
Here is the full code to greet everyone:
people = ['Rachel', 'Monica', 'Phoebe', 'Ola', 'You'] for name in people: print('Hi ' + name + '!') print('Next person')
And when we run it:
Hi Rachel! Next person Hi Monica! Next person Hi Phoebe! Next person Hi Ola! Next person Hi You! Next person
As you can see, everything you put inside a
for statement with an indent will be repeated for every element of the list
Let’s look at another application of the
for...in loop we just looked at, and apply it to something you may find yourself doing often. Suppose you find the sum of all the elements in a list. This is how we can go about it:
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] sum_so_far = 0 for element in lst: sum_so_far = sum_so_far + element print(sum_so_far)
Awesome! Let’s fully understand what’s going on in the code above:
- On line 1, we define our list
lstwith the numbers we want to sum up.
- Next, on line 2, we initialize a variable
sum_so_farwith 0. This variable stores the sum after the current element in the list has been added.
- Line 3 starts the
for ... inloop as usual. Here
elementis a variable that temporary stores the current value in the
lstlist as we iterate over it.
- Line 4 is by far the most important line. Here, we update
sum_so_farto increase by the value of the current element in the list.
Here’s what the value of
sum_so_far looks like over the 10 iterations:
End of iteration #1: element = 1, sum_so_far = 1 End of iteration #2: element = 2, sum_so_far = 3 End of iteration #3: element = 3, sum_so_far = 6 End of iteration #4: element = 4, sum_so_far = 10 End of iteration #5: element = 5, sum_so_far = 15 End of iteration #6: element = 6, sum_so_far = 21 End of iteration #7: element = 7, sum_so_far = 28 End of iteration #8: element = 8, sum_so_far = 36 End of iteration #9: element = 9, sum_so_far = 45 End of iteration #10: element = 10, sum_so_far = 55
- On line 5, once the
for-loop completes and we have added all the elements, we print out the final value of
Great, you can now sum up all the numbers in a list! Ready for a quiz?
You can also use
for with the
for i in range(1, 6): print(i)
Which would print:
1 2 3 4 5
range is a function that creates a list of numbers. It works as follows:
range(n)function returns the numbers 0, 1, … n-1
range(a, b)returns a, a+1, … b-1 — up to but not including the last number.
Note that the second of these two numbers is not included in the list that is output by Python (meaning
range(1, 6) counts from 1 to 5, but does not include the number 6). That is because “range” is half-open, and by that we mean it includes the first value, but not the last.
Python also has another loop called the
while loop. The while loop runs as long as the condition inside the while is
In that sense, a while loop is almost like an
if-statement, except the code doesn’t run just once, but keeps executing again and again as long as the statement is
You may be wondering why we need another loop at all when we already have a for loop. For loops are great when we know the number of times we want to run the loop in advance — they are great for going over lists, for going over a range of numbers, and so on. On the other hand, a while loop is just perfect when we don’t know the number of executions in advance, but all we know is that we need to do something as long as something is True. It may have to run once, 10 times, 100 times, or maybe, not even once!
For example, suppose we want to write a program that prints all the power of 2 less than 100. We don’t know at the outset how many lines we’re going to print. This is a perfect opportunity to use a while loop:
current_value = 2 while current_value < 100: print(current_value) current_value *= 2
The output looks like this:
2 4 8 16 32 64
Wow! We just used a while loop effectively — we didn’t know how many times we’ll need to run the loop. All we knew was the termination condition.
Note that in a theoretical sense,
while-loops are equivalent. What we mean by that is, every
for-loop can be re-written as a
while-loop, and every while loop can be re-written as a
For example, let’s take our people list from above and write the greeting program using a
people = ['Rachel', 'Monica', 'Phoebe', 'Ola', 'You'] i = 0 while i < len(people): print('Hi ' + people[i] + '!') print('Next person') i = i + 1
Notice a number of important things that we had to take care of while writing the while loop:
- On line 2, we had to declare a new variable
iwhich stores the current index. This index,
i, not only lets us access the elements one by one, but we also use its value to check if the
while-loop should stop running.
- On line 3, notice the condition for the while loop to keep running
i < len(people). Note that we used
<=since the index of the last element in the list
'You'is 4 (indexes start with 0, remember?). 4 is one less than the number of elements in the list (which is 5). So, when
iis 5, we should not enter the
while-loop at all, which is why we used
- On lines 4 and 5, we print what we want.
- On line 6, we do something very important — we actually update the value of
iand increase it by 1. It’s very important to get this right. If we forgot to write this statement, our
while-condition will always stay
True, and the loop will keep running forever! This is called an infinite loop — and is obviously something you don’t want in your program.
If it seems like your
while-loop is not terminating, and is just repeating itself over and over, you should check your
while-condition, and make sure you’re updating the variables inside the loop-body so that the condition actually becomes
False when you’re done.
But most of the time, you will use a for loop when you have a list / range. On the other hand, you will use a while loop when you want to stop based on a condition.
continue give us some more control over what code is executed inside a loop.
break is encountered, Python immediate stops iterating over the loop (it also ignores all the code after the
break within the loop body, if any). Here’s an example:
a = [1, 5, 3, 2, 4, 6, ] for element in a: print(element) if element == 2: break # quit the loop when element == 2 print(-element) # when element == 2, this line too won't execute
Here’s the code output:
1 -1 5 -5 3 -3 2
Note: 4 and 6 don’t get printed at all. 2 gets printed, but -2 does not, since
break happens before that.
continue is encountered, Python ignores the code after the
continue within the block, but “continues” iterating over the rest of the elements. Here’s an example:
a = [1, 5, 3, 2, 4, 6, ] for element in a: print(element) if element <= 2: continue # don't execute the rest if element <= 2 print(-element) # when element <= 2, this line too won't execute
Here’s the code output:
1 5 -5 3 -3 2 4 -4 6 -6
Note: All numbers get printed. However, for 1 and 2, the negative values don’t get printed because of the
continue can be used inside
while-loops as well.
Awesome! In this tutorial, you learned about:
- for loops — help us iterate over our lists.
- the range() function — helps us specify a list of numbers.
- while loops — help us keep a code block running as long as a condition is True
- break and continue — give us more control over our for and while loops
Based on content from https://tutorial.djangogirls.org/en/python_introduction/