Lesson 9: Loops
Types of Loop
There are 2 types of loop in Python:
- For Loop
- While Loop
For Loop
A for loop is a block of code that repeats itself for every item in a list. The most basic for loop iterates through a user provided list.
For example, let’s look at a list of vegetables:
- potato
- carrot
- parsnip
- spinach
If we applied a for loop to this list, it would run 4 times.
Here is an example of how we might use a for loop to print all the vegetables in our list:
vegetables = ['potato', 'carrot', 'parsnip', 'spinach'] for vegetable in vegetables: print(vegetable)
For Loop for a Range
We can also use a for loop to iterate through a range of numbers. To do this we simply replace the list (e.g. vegetables in the above example) with range(x) where x is a number. The range will automatically start from 0 and x represents the number after the last number for the range. For example, if we wanted to loop through every number from 0 to 5 we would use range(6).
Try It!
Change the number in this code and click play to see what happens:
If we do not want the range to start at 0 we can also provide a start number in our code. Unlike the end number, the start number is included in the range. For example, if we wanted to loop through all numbers from 4 to 7 we would use range(4, 8)
Try It!
Change the numbers in this code and click play to see what happens:
Python also allows you to provide an interval for a range by supplying a third number to range(). Here is an example of how you would print every third number between 4 and 21:
for x in range(4, 22, 3): print(x)
For Loops for a String
When we provide a string to a “for loop” instead of providing a list, the loop will iterate through each character in the string.
count = 0 for x in 'Mississippi': if (x == 'i'): count += 1 print(count)
This example counts how many occurrences of the letter i there are in Mississippi. It iterates through each letter in the string and checks if the letter is an i. If it is then it increases the variable count by 1. If it is not, then it simply moves on to the next letter.
While loop
A While Loop is a block of code that is repeated while a condition is true. Here is an example of a potato counter which prints the count of potatoes while the there are less than 4:
potatoCount = 1 while potatoCount < 4: print(potatoCount, "potato") potatoCount += 1
Try It!
Change the following code to see what happens:
Loop Statements
Break
A break statement can be used to exit a loop. If it is a for loop it will exit before it has finished iterating through the list. If it is a while loop it will exit regardless of whether the while condition is true or false.
Try It!
This example uses the _break_ statement in a for loop to stop printing letters once it has printed the letter c. Press play to see the result.
Continue
A continue statement can be used to skip an iteration of a loop and continue to the next iteration.
Try It!
Here is an example of a for loop which prints every letter from a to g excluding c. Press play to see the result.
Else
An else statement can be used to execute some code immediately after a loop has finished iterating.
Try It!
Here is an example of a for loop which prints _The End!_ after it has finished iterating. Press play to see the full result:
Nested Loops
A nested loop is a loop that exists within another loop. Here is an example of a _for loop_ nested inside another _for loop_.
vegetables = ['potato', 'carrot'] vegetableCount = [1, 2] for vegetable in vegetables: for count in vegetableCount: print(count, vegetable)
The print statement in the above example will execute a total of 4 times. The inner loop (vegetableCount) is executed fully for each iteration of the outer loop (vegetables).
Try It!
Infinite Loop
An infinite loop is a loop that never stops executing. This usually happens due to an error in the code. Here is an example of an infinite loop:
myNumber = 2 while myNumber > 1: print(myNumber) myNumber += 1
In this example myNumber will always be greater than 1 so the while loop will never stop executing. This can cause a page to crash or load slowly. We could fix this by subtracting 1 from myNumber in each iteration instead of adding 1 like we are in the example.
Try It!
Fix the inifinite loop:
Resources