Python Loops: “For Loop” and “While Loop” How and when to use them?
Introduction
Python Loops are an important part of Python programming because they allow you to execute a block of code repeatedly until a certain condition is met. There are two types of loops in Python: for loops and while loops. In this tutorial, we will cover the syntax of “for loop” and “while loop” and how and when to use them. I have also provided some real-life examples of how they can be applied with code samples.
For Loops
Python “for loop” is used to iterate over a sequence (such as a list, tuple, string, or range). A “for loop” has the following syntax:
In the code snippet above, replace "variable" with the name of the variable you want to use and "sequence" with the name of the sequence you want to iterate over in this code snippet. Also, replace "# Code to be executed" with the actual code you want to run for each loop iteration.
Let’s look at some examples.
Iterating through a list
Iterating through a string
Iterating using a range.
Let’s look at a real-life example.
Summing the prices of items in a shopping cart
Assume you have a shopping cart with various items and their prices. A for loop can be used to iterate through the list of prices and add them together to calculate the total cost.
Here is the code snippet below.
Let’s explain the code snippet above.
The code generates a dictionary called "shopping cart" that contains the names of four items (apples, bananas, cherries, and oranges) as keys and the prices of those items as values. The code then sets the variable "total cost" to zero. The "for loop” iterates over the dictionary values (i.e. the prices of the items) using the "values()" method, adding the value to the "total cost" variable with each iteration. In the end, the code prints the total cost of all the items in the shopping cart by displaying the value of the "total_cost" variable.
While Loops
While loops are used to execute a block of code repeatedly as long as a given condition is true. A while loop has the following syntax:
The "condition" is a Boolean expression that is checked before each loop iteration. If the condition is met, the indented block of code is executed, and the condition is then re-evaluated for the next iteration. The loop will continue until the condition is met.
Let’s look at some “while loop” examples!
Counting from 1 to 5
This example shows a simple while loop that counts from 1 to 5 and prints the results.
The condition, in this case, is “i <= 5". The loop will continue to iterate as long as “i” is less than or equal to 5. The current value of “i” is printed inside the loop, and then it is increased by one. The loop will keep iterating until “i” is greater than 5.
Summing the values in a list
This example shows a while loop that adds up the values in a list.
The condition, in this case, is “i < len(numbers)". The loop will continue to iterate as long as “i” is less than the length of the numbers list. Within the loop, the current list element is added to the total variable, and then “i” is increased by one. The loop will keep iterating until “i” equals the length of the numbers list.
Real-life examples
Real-life example: bank account withdrawals
Let’s assume you have a bank account with a specific balance and want to withdraw a fixed amount of money each month. A while loop can be used to calculate how long it will take to deplete the account.
The code sets the variables "balance" to 5000, "monthly withdrawal" to 200, and "months" to 0 at the start. It then enters a "while loop," which runs indefinitely as long as the "balance" is greater than zero. The code within the loop subtracts the "monthly withdrawal" from the "balance" and adds one to the "months" variable. The loop ends when the "balance" falls to zero or less, and the code prints a message indicating how many "months" it took to deplete the account.
Conclusion
In this tutorial, we covered the fundamentals of Python for loops and while loops, as well as real-world examples and code samples for each. Loops are a powerful programming tool that allows you to execute code multiple times based on certain conditions. You can write more efficient and effective Python programmes if you understand loops.