Loops
Looping is a control flow statement that is used to repeatedly execute a group of statements as long as the confition is satisfied. There different type of *control flow statements” in python. Here’s the most used.
The following table summarizes the main characteristics of each loop:
Loop Type | Description |
---|---|
For-loop | A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). |
While-loop | With the while loop we can execute a set of statements as long as a condition is true. |
for-loop
There are multiple ways to use a for-loop. Here’s some examples.
For-loop in-range
# This is a simple loop for i in range(10): print(i)
For-loop with list
# This is a loop with a list my_list = ["a", "b", "c"] for i in my_list: print(i)
For-loop with list and index
# This is a loop with a list and index my_list = ["a", "b", "c"] for i, item in enumerate(my_list): print(i, item)
While-loop
The while-loop is used to repeat a block of code as long as the condition is true. Here’s an example.
# This is a while loop
# It will run until the condition is true
i = 0
while (i < 10):
print(i++)
Break
The break statement is used to exit a loop. Here’s an example.
# This is a while loop
# It will run until the condition is true
# or until the break statement is called
i = 0
while (i < 10):
i += 1
print(i)
if i == 5:
break
🛠 Exercises
01: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 02: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 03: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍
Solutions:
01: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 02: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 03: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍