The ability to repeat tasks many times in rapid succession is one of the things which makes computers so useful. In programming, the technical word for repeating things is iteration. This is generally carried out using some kind of loop.
Python offers several different ways to implement loops, and the best choice is determined by the situation. We are going to look at some different ways to create loops in Python, and discuss when each is appropriate. Code samples are provided for illustration. To get good at using loops in Python, you should try typing and running all of the examples for yourself, and then make modifications and experiment to see if you can get the different types of loop to work in the way you want them to.
For Loop Version 1
my_string = "Hello World!"
for index in range(len(my_string)):
print("index: ", index, "value:", my_string[index])
The output for this code is:
index: 0 value: H
index: 1 value: e
index: 2 value: l
index: 3 value: l
index: 4 value: o
index: 5 value:
index: 6 value: W
index: 7 value: o
index: 8 value: r
index: 9 value: l
index: 10 value: d
index: 11 value: !
This version makes use of the range function. range()
takes upto 3 arguments: the initial value, the end value, and a step. By default the initial value is 0 and the step is 1. The end value is actually one short of the value given, due to the fact that indices are counted from zero.
Take a close look at the code and output and see if you can understand what is happening. The key point is that the index
variable starts as 0
and is incremented by 1
each time through the loop until the final value is reached. During each loop, the character at the position index
is accessed and printed.
This type of loop is generally used when you want to have access to the index numbers in a string or list you are looping through (or iterating over).
- Use when you know how many times you need to repeat
- Use the
range()
function - Use when you need access to the index/position number
For Loop Version 2
If you don’t need to explicitly reference the index within a string or list, but just need the value, Python provides an elegant syntax, as follows:
my_string = "Hello World!"
for char in my_string:
print(char, end="")
Output:
Hello World!
The result may not look that impressive, since we could have just printed my_string
directly, but we are learning concepts here. The loop iterates through the values of my_string
, and the end=""
prevents each print statement starting on a new line.
- Use when you know how many times you need to repeat
- Uses
for item in
string/list - Use when you don’t need the index
Python Enumerate
Python offers a really handy way to get access to both the index and the value at each index when looping/iterating through a list, string etc. This is by using enumerate()
.
my_string = "Hello World!"
for idx, val in enumerate(my_string):
print("index:", idx, "value", val)
- Use when you need access to both the index and the value.
While Loops
Another way of looping in Python, which is used when we don’t know in advance how many iterations will be needed, but instead want to base exiting the loop on some condition is a while
loop.
my_string = "Hello World!"
counter = 0
while counter < len(my_string):
print(my_string[counter], end="")
counter = counter + 1
In the above example, although we know the length of my_string
, the program doesn’t, so we keep checking whether the counter is less than the length of the string, and when it isn’t, we exit. This is not a common way to use a while
loop, as a for
loop would be more appropriate, but I wanted to show you how the same effect as what we have done with for
loops could be achieved. In a future article we will look in more detail at while
loops`.
- Use when you don’t know how many times you need to repeat Use a condition to decide whether to continue You need to manually control the count
Conclusion
Looping, AKA, iteration, is a fundamental skill in computer programming. This article has shown examples of how to use some of the basic constructs available in Python for creating loops. I hope you have found it helpful.