In Python, loops and iterations are used to execute a block of code repeatedly until a certain condition is met. They are powerful constructs that can help you automate repetitive tasks and iterate over collections of data.
The while loop is used to execute a block of code as long as a certain condition is true. The general syntax of a while loop is:
while condition: # code to be executed
Let’s start with a simple example. Consider a scenario where you want to print the numbers 1 to 5. The following code demonstrates how to achieve this using a while loop:
counter = 1 while counter
In this example, we initialize a variable called counter with a value of 1. The loop condition counter checks if the value of counter is less than or equal to 5. If the condition is true, the code inside the loop is executed, which includes printing the current value of counter and incrementing it by 1 using counter += 1 so that the loop eventually terminates. The output of this code will be:
1 2 3 4 5
As long as the condition is true, the loop will keep iterating. It’s important to ensure that the loop has an exit condition; otherwise, it may lead to an infinite loop.
The for loop is used to iterate over a sequence (such as a list, tuple, or string) or other iterable objects. The general syntax of a for loop is:
for item in iterable: # code to be executed
Let’s see an example that iterates over a list of fruits:
fruits = ["apple", "banana", "orange"] for fruit in fruits: print(fruit)
In this example, the for loop iterates over each item in the fruits list and executes the code inside the loop, which includes printing the current item. The output will be:
apple banana orange
The for loop automatically assigns each item of the list to the variable fruit during each iteration.
Within both while and for loops, you can use control statements like break and continue to modify the flow of execution.
The break statement is used to exit the loop prematurely when a certain condition is met. For example:
counter = 1 while counter
In this modified example, the loop will terminate when counter is equal to 3, using the break statement. The output will be:
1 2
The continue statement is used to skip the rest of the code in the current iteration and move to the next iteration. For example:
counter = 1 while counter
In this modified example, the loop skips printing the number 3 and moves to the next iteration using the continue statement. The output will be:
1 2 4 5
These control statements provide flexibility and allow you to control the flow of your loops based on certain conditions.
With the knowledge of while and for loops, you have the ability to iterate over data and perform actions efficiently. Practice writing loops with different scenarios to solidify your understanding of this fundamental concept in Python.