Python loops¶
Loops are used in Python to iterate over collections, lists, arrays, and other iterable data structures^[400-devops__09-Scripting-Language__python__introduction__README.md]. The language provides two primary primitive loop constructs: for loops and while loops^[400-devops__09-Scripting-Language__python__introduction__README.md].
While loop¶
The while loop executes a block of code as long as a specified condition remains true^[400-devops__09-Scripting-Language__python__introduction__README.md]. It is often used when the number of iterations is not known in advance, or for simple conditional iteration.
To use a while loop, an index variable is typically initialized before the loop starts and updated within the loop block^[400-devops__09-Scripting-Language__python__introduction__README.md].
i = 0
while i < 7:
print(customers[i])
i += 1
This structure is common when iterating through arrays by index, where the loop continues until the index counter exceeds a certain value^[400-devops__09-Scripting-Language__python__introduction__README.md].
For loop¶
The for loop is generally preferred when iterating over dictionaries or lists because the syntax is often simpler than managing a manual counter^[400-devops__09-Scripting-Language__python__introduction__README.md]. It iterates over the elements of a sequence directly.
When working with dictionaries, a for loop can be used to access keys, which are then used to retrieve the corresponding values^[400-devops__09-Scripting-Language__python__introduction__README.md].
customers = getCustomers()
for customerID in customers:
print(customers[customerID])
In this example, the loop variable customerID takes on the value of each key in the customers dictionary, allowing the code to access and print the specific customer record for that key^[400-devops__09-Scripting-Language__python__introduction__README.md].
Related Concepts¶
- [[Python control flow]]
- [[Python dictionaries]]
- Python classes and objects
Sources¶
- 400-devops__09-Scripting-Language__python__introduction__README.md