| DJC | Tutorials | Python |

for and while Loops in Python - DJC

Loops allow you to repeat a block of code multiple times.

for: iteration over collections

It is used to iterate through elements of a sequence (list, tuple, string, etc.).

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

It can also be used with the range() function:

for i in range(5):
    print(i)  # Prints from 0 to 4

while: repetition while a condition is true

The while loop runs as long as the condition is true.

counter = 0

while counter < 5:
    print("Counter:", counter)
    counter += 1

Caution:

A poorly defined while loop can cause infinite loops if the condition never becomes false.

| DJC | Tutorials | Python |