Looping
In the earlier blogs we used a “For Loop” to iterate (or explore) through items in a collection and in this blog, we will explore the two different kinds of looping mechanisms that we can use in Python.
The two types of loops in Python are:
- For Loop
- While Loop
NOTE: Don’t forget that when using a loop mechanism, the block of code within it must be indented with 4 spaces.
For Loop
The For Loop allows us to iterate through each item within a collection (such as list, tuples, dictionaries, sets, etc.} and through the use of a For Loop, we can use all or some of the items of a collection as we wish to.
The syntax of a For Loops is:
for <new_variable> in <collection> ….loop-code-line-1 ….loop-code-line-2 . . ….loop-code-line-n
Consider the following example:
item_list = ["Python", "Blogs", "For Loops"] for item in item_list: print(item) print("\nFor loop end")
We should get:
Here we created a list of items at the beginning, and then we used the For Loop on this list to print out each item. Here ‘item’ is a new variable that is created for the For Loop, and it stores each value of the list for each respective iteration.
Let’s consider another way to use the For Loop:
numbers_list = [1, 2, 3, 4, 5] total_variable = 0 # A variable to store the sum of the items in the above list for number in numbers_list: total_variable += number print("The sum of the list of numbers is:", total_variable) # This prints 15
We would get the following result:
Here the variable ‘total_variable’ is created with 0 and will be used to store the sum. In the For Loop the variable ‘number’ will first be 1, then 1 will be added to ‘total_variable’ {so it’ll be 0+1}. Then the next item will be 2, so ‘number’ will have 2, and then 2 will be added to the 1 stored in ‘total_variable’. Likewise, this will continue till the last item which is 5 and will finally give the output as 15.
Replace the above For Loop with the one given below, if you wish to see to each step of the iteration.
for number in numbers_list: print("total_variable before adding is:", total_variable) print("number is", number) total_variable += number print("total_variable after adding is:", total_variable) print("")
We can also selectively use items from a collection, consider the following example using the range() function:
table_of_three = [] for number in range(1, 51): if number % 3 == 0: table_of_three.append(number) print(table_of_three)
Here we created an empty list, which as the name suggests will store the table of three. Remember the range() function? In this case, it generates a list of numbers from ‘1’ to ‘50’, and we will use the For Loop to iterate through this list of numbers. Then we use the if condition to check if each value in the list, can be divided by 3. (‘%’ denotes the remainder, and if a number can be divided then the remainder should be 0.)
Recall how we used the append() function to add items to a list? In the same way, we only add a number to the list, if it can be divided by 3, and then finally we print out the list.
While Loop
The While Loop is a loop that runs continuously till a True condition becomes False or until we break out of the while loop. The syntax of a While Loop is:
while <condition>: ….loop-code-line-1 ….loop-code-line-2 . . ….loop-code-line-n
Consider the following:
list_variable = [0, 1, 3, 4, 5, 6, 7, 8, 9] i = 0 while list_variable[i] < 5: print(list_variable[i]) i += 1
Here we have created a list that stores numbers from 0 to 9. Then we created a variable ‘i’ which stores 0, this is because we will use ‘i’ to represent the index number of each item of the list.
The condition we have given the While Loop is that as long as the item is less than 5, Python must continue the loop, and the loop must end as the item becomes equal to or greater than 5.
Take a look at how we can use Boolean variables with the While Loop:
list_variable = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] i = 0 condition_ = True while condition_: print(list_variable[i]) if list_variable[i] == 3: condition_ = False i += 1
Here (built on the previous example) we created a variable ‘condition_’ which stores True, and we are telling Python to run the While Loop as long as this variable is True. However, within the While Loop, we tell Python to turn the variable ‘condition_’ to False if the item becomes 3.
Break and Continue Keywords
Python also offers two other keywords which we can use, most notably in our loops. The “break” keyword tells Python to stop the execution of the loop, and the “continue” keyword tells Python to skip the current iteration and move to the next iteration.
Let’s look at an example:
name = "Verification Master" i = 0 while name == "Verification Master": i += 1 if i == 4: continue # skip 4th iteration if i == 7: break # end while loop output_string = name + " " # adding whitespace to our name string print("Iteration", i) print(output_string * i) print("") # makes the output pretty
If our name is “Verification Master”, we print it ‘n’ times depending on the nth iteration. When ‘i’ is 4 we skip the execution of that iteration and move on to the next one. Finally, when ‘i’ is 7 we stop the loop entirely.
What have we learned?
•What are the different types of loops in Python?
•What is the primary difference between the For and While loop?
•How do we use the range() function with the For Loop?
•What does the % operator indicate?
•How can we use Boolean values to break out of a While Loop?