Any changes you make to the code on this page, including your solutions to exercises, are temporary. If you leave or reload the page, all changes will be lost. If you would like to keep your work, copy and paste your code into a separate file or editor where it can be saved permanently.
Loops are used to repeat a block of statements multiple times.
5.1 While loops
We first look at while loops, where statements are repeated as long as a given condition remains True:
while condition:# Code block of to be repeated as long as the `condition` is True
Example. To print all numbers from 1 to 10, we can use the following code:
Question. What would happen if we did not include the line i = i + 1?
Solution. If we forget to update the loop variable (i) inside a while loop, the condition may never become False, and the program will run forever (infinite loop).
Exercise. Print each letter of a given string on a separate line using a while loop and the indexing operator [].
Sample solution
string ='Hello!'i =0while i <len(string):print(string[i]) i +=1# Recall that this is a shorter way how to write i = i + 1
Exercise. Calculate the sum of all integer numbers between 1 and 10000 (inclusive) using a while loop.
Sample solution
sum_ =0current =1while current <=10000: sum_ += current current +=1print(sum_)# Notes:# - Avoid using the variable name `sum` (there is a built-in function called `sum`)!# - Pay attention to the first and the last iteration.# Are we adding 1 in the first iteration and 10000 in the last iteration?
50005000
5.2 For loops
We can use a for loop to iterate over all elements of a list, a range of numbers, a string or, more generally, any iterable object (an object that is capable of returning its elements one by one). The for loop executes a block of statements for each element:
for variable in iterable:# Code block to be repeated for each element of `iterable`# Usually involving `variable` that stores the value of the current element# in each iteration of the loop
Example:
We can also use a for loop with range to iterate over numbers:
The range(stop) function generates numbers starting from 0 up to, but not including, the specified stop value. range(start, stop) lets us start at a different start value. range(start, stop, step) also lets us define the step size.
Strings are iterable too, we can loop through all characters:
NEVER modify a list while iterating over it!
Caution
Some elements get skipped because the list is being shortened while looping over it. If we need to filter a list, we should build a new list instead:
new_list = []for element in alist:if some_condition(element): new_list.append(element)
5.3 When to use while vs. for
We have seen two types of loops. But when to use a while and when a for?
Use a while loop when you don’t know in advance how many iterations are needed (e.g., keep asking for input until user enters “quit”).
Use a for loop when you know the number of iterations, want to go through all elements of a list (or more generally, an iterable).
5.4 Continue and break
We can skip the current iteration and move on to the next one, using continue. The following example prints numbers from 1 to 10 that are not divisible by 2 or 3:
Exercise. What would happen if we moved i += 1 after the if statement?
We can exit a loop completely using break. In the following example, each character of a given string is printed on a separate line until the first exclamation mark !:
Sometimes it might be convenient to create an infinite loop and use break to exit:
shopping_list = []whileTrue: item =input("Item to add to your shopping list (or press Enter to exit): ")if item =="":break shopping_list.append(item)print("Your shopping list:")for item in shopping_list:print(f"- {item}")
5.5 Common mistakes to avoid
5.5.1 Forgetting to update variables in a while loop
Caution
Wrong code:
i =1while i <=10:print(i) # Infinite loop (`i` never changes)
Correct code:
5.5.2 Off-by-one errors with range
If we want to loop through the numbers from 1 to 10 (inclusive), the following code is wrong:
CautionWrong code
for i inrange(1, 10): # Stops at 9, not 10print(i)
The correct code is:
Always think carefully about the first and last iteration values.
5.5.3 Modifying a list while iterating
Caution
Wrong code:
alist = [1, 2, 3, 4]for element in alist:if element %2==0: alist.remove(element) # Do not modify the list you are iterating!
Correct code:
5.6 Summary
# While loopwhile condition:# repeat while condition is True# For loopfor variable in iterable:# repeat for each element of iterable# Range functionrange(stop) # 0, 1, ..., stop-1range(start, stop) # start, start+1, ..., stop-1range(start, stop, step) # start, start+step, ...# Common statements inside of loops:continue# skip to next iterationbreak# exit the loop entirely