The Concept of Loops in Python
2024-06-14A loop is a method used to perform repetition or iteration over a sequence of data. This method is useful when working on data processing tasks that require repetition or looping through a sequence or collection of elements within the data.
Imagine you have 100 plants in a garden, and you need to water each plant one by one. Essentially, what you’re doing is “looping” the task of watering 100 times. The sequence of activities might look like this:
1. Start with the first plant.
2. Water the plant.
3. Move to the next plant.
4. Repeat watering until all 100 plants are done.
In the analogy above:
• The row of plants is the data sequence being iterated.
• Watering each plant is the block of code executed during each iteration.
• Moving to the next plant is moving to the next element in the sequence.
This process will repeat until all the plants are watered.
Python provides two main ways to perform loops: the for loop and the while loop. The difference lies in how many times the loop will be executed. The for loop is used when the number of iterations is known, while the while loop is used when the number of iterations is uncertain.
For Loop
The for loop is used to iterate over a sequence such as a list, tuple, dictionary, set, or string.
To create a for loop, you use the for keyword to refer to each element in the sequence, followed by the keyword in and the data sequence to be iterated.
for variable in sequence:
# code block to execute
This syntax can be read as “for each variable in a sequence, execute the following code block.”
Examples:
- Iterating through a list:
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
print(fruit)
Output:
apple
banana
orange
- Iterating through a tuple:
coordinates = (10, 20, 30)
for coord in coordinates:
print(coord)
Output:
10
20
30
- Iterating through a string:
text = "python"
for char in text:
print(char)
Output:
p
y
t
h
o
n
- Iterating through a dictionary:
ages = {"Aldo": 15, "Budi": 10, "Tuti": 17}
for name in ages:
print(name, ages[name])
Output:
Aldo 15
Budi 10
Tuti 17
While Loop
A while loop is used to iterate a block of code as long as a given condition is met. This is known as “indefinite iteration,” meaning the loop will continue as long as the specified condition is true.
To create a while loop in Python, you need the while keyword, which sets the condition for the iteration.
while condition:
# code block to execute
Example:
count = 0
while count < 5:
print(count)
count += 1 # increment count by 1
Output:
0
1
2
3
4
One use case for a while loop is user validation on a platform. For example, when accessing a bank account, there might be a limit of 5 attempts to log in. This process can be handled with a while loop. Here’s a possible code implementation:
attempts = 0
password = ""
while attempts < 5 and password != "secret":
password = input("Enter your password (attempt {}): ".format(attempts + 1))
if password != "secret":
print("Incorrect password. Try again.")
attempts += 1
if password == "secret":
print("Access granted!")
else:
print("You've exceeded the allowed number of attempts. Your account is locked.")
The beauty of programming is that there's always something new to learn. The learning process is never-ending, and that's what keeps it exciting. This is my ongoing journey into the world of programming. I'm constantly learning and growing, and I'm excited to share my experiences with you as I progress.
const developerName = "Ano Jumisa"