Python, a language that has become highly popular in application development, continues to be our focus. In this tutorial, we will advance our understanding by exploring loops in Python and how to manipulate them.
Previous tutorial: #7 – Dictionaries
Python for – while – Loops
For Loops
The first loop we’ll explore is the “for” loop, a staple in all development languages. This loop executes the code a specified number of times.
In the example below, we instruct the program to display the incremented number five times. The only nuance to note is that the increment starts at 0, not 1.
for x in range(5):
print(x)
This will display: 0 1 2 3 4
Looping Over a List
We’ve previously seen how to create lists (refer to the tutorial); it’s worth knowing that you can loop over a list to make better use of it.
Here’s a simple example to understand how to loop over a list, displaying each element one by one.
users = ["czero", "batman", "robin", "robocop"]
for oneUser in users:
print(oneUser)
On each iteration, the loop takes the next element from the “users” list and puts it into the variable “oneUser.” This will display: czero batman robin robocop.
Looping Over a Dictionary
Just as we’ve seen how to create dictionaries before (refer to the tutorial), it’s possible to loop over them for better utilization.
Here’s a simple example to understand how to loop over a dictionary, displaying each element one by one.
monId = {
"nom": "judicael",
"age": "42",
}
for element in monId:
print(element)
On each iteration, the loop takes the key of the next element from the “monId” dictionary and puts it into the variable “element.” This will display: nom age.
You can easily display the values using the “element” variable, as seen in the example below:
monId = {
"nom": "judicael",
"age": "42",
}
for element in monId:
print(element + " : " + monId[element])
This will display:
nom : judicael
age : 42
While Loops
The Do While loop doesn’t exist in Python, but here’s a workaround to achieve it: article to read.
The “while” loop allows you to choose the condition. The contents of the loop will be continuously executed as long as the condition is valid.
currentValue = 0
maximum = 5
while currentValue < maximum:
print(currentValue)
currentValue += 1
On each iteration, the “currentValue” variable will increment by 1, executing the loop condition five times.
Conclusion – Python for – while Loops
We have explored loops in Python, which are essential to know for creating quality programs. We will delve deeper in the next chapter of our Python learning journey, which still holds many secrets.
Next Chapter: #9 – Classes and Objects
Be the first to comment