Mastering Loops in Python: Automate Your Code with Efficiency and Ease
As an IT specialist, you can encounter situations where you must reuse a piece of code multiple times. For instance, when automating the collection of new registrations or applications on a website. Instead of repeatedly writing the same line of code, which is time-consuming and inefficient, you can create a function or use so-called loops.
Case study — loop for product codes
We will consider here one example that showcases the loops usage of the self-purchase systems found in stores. These systems allow customers to make purchases by entering product codes. To ensure a smooth and efficient experience, these systems typically employ a loop that checks for code entry every 20 seconds. This loop verifies whether the code has been typed, allowing customers to complete their transactions seamlessly.
You can use a few key loop options using Python’s range() function. The statement block within the loop is executed based on a condition checked at the beginning or end of each iteration.
There are two key options for conditional loops in Python:
- For loop
- While loop
Both options allow you to execute a piece of code repeatedly. The main difference between these two functions is quite clear. If we know the exact number of iterations in advance, we will use the “for” loop; otherwise — the “while” loop.
1. For loop
This function for
allows you to repeatedly execute a block of code for each item in the sequence, like in our case. Four possible data types can be used infor
loop, in particular, a list, tuple, string, or range.
We will elaborate on this point in more detail. Here are some examples of how the for
loop can be used:
- Iterate over a list:
python
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
print(fruit)
Output:
apple
banana
orange
2. Iterate over a string:
python
message = "Hello, World!"
for char in message:
print(char)
Output:
H
e
l
l
o
,
W
o
r
l
d
!
3. Iterate over a range of numbers:
python
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
Solution For loop
We will use the ‘a list ‘ option since we want to iterate a list of product codes. So, let’s define the codes according to UPC (The Universal Product Code), which consists of 12 digits uniquely assigned to each trade item. It’s a sample data structure used for demonstration purposes.
Step 1: Define the product codes
python
product_codes = ["018375768312", "035674982241", "048293746356"]
After defining the list of products, we need to use for in function to iterate the code entry verification. In this case, we will use the function print to show the message about the verification.
Step 2: Perform the code checking loop
2.1. Specify a message
python
for code in product_codes:
print("Checking code:")
2.2. Specify the number of iterations
Since our task is to check the code every 20 seconds, we must use the module import time
. Python offers a wide range of modules you can import for various purposes. For example, math
, random
, os
, json
, etc. The time
module in Python provides multiple functions to work with time-related operations. We import the time
module to use the sleep()
function, which allows us to introduce a delay in the code execution.
import time
import time
for _ in range(3): # Replace 3 with the desired number of iterations
code = input("Enter the product code: ")
3. Specify the interval between code checks
python
import time
# Simulating the 20-second interval
time.sleep(20)
Thus, the unified code will look like this
import time
product_codes = ["018375768312", "035674982241", "048293746356"]
for code in product_codes:
print("Checking code:", code)
time.sleep(20)
Output:
Checking code: 018375768312
Checking code: 035674982241
Checking code: 048293746356
2. While loop
Another option is the while
loop. This while
loop accomplishes the same behavior as the for
loop in the previous example. It iterates over each code in the product_codes
list, prints the message, and waits for 20 seconds before moving on to the next code.
import time
product_codes = ["018375768312", "035674982241", "048293746356"]
index = 0
while index < len(product_codes):
code = product_codes[index]
print("Checking code:", code)
index += 1
time.sleep(20)
So, we have already viewed why and how to use import time
and define product_codes. The novelty of this statement will be the usage of variables while index
. We initialize the index
variable to 0, which represents the current position in the product_codes
list.
The while
loop continues to execute as long as the index
is less than the length of the product_codes
list. Inside the loop, we retrieve the code at the current index
from the product_codes
list using product_codes[index]
.
We then print the message “Checking code:” followed by the code. After printing, we increment the index
by 1 to move to the next code in the list. Finally, we use time.sleep(20)
to introduce a 20-second delay before the next iteration of the loop.
It’s important to be cautious when using while loops to avoid creating infinite loops that don’t terminate. Ensure to include a condition that will eventually be met to exit the loop.
In conclusion, both for and while loops are powerful tools in programming that allow you to automate repetitive tasks. Understanding their syntax and usage allows you to optimize your code and improve efficiency.