Used to iterate over iterable objects like lists, strings, or ranges.
for i in range(5):
print("Hello", i)
Output:
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4
Repeats until a condition becomes False.
x = 0
while x < 3:
print("x =", x)
x += 1
The input() function prompts the user and returns a string.
name = input("What's your name? ")
print("Hello", name)
Any iterable object like a list or string can be converted into an iterator.
my_list = [10, 20, 30]
iterator = iter(my_list)
print(next(iterator)) # 10
print(next(iterator)) # 20
print(next(iterator)) # 30
for index, value in enumerate(["a", "b", "c"]):
print(index, value)
names = ["Ali", "Sara"]
scores = [80, 90]
for name, score in zip(names, scores):
print(name, score)
From the random module, used to reorder list items randomly.
import random
items = [1, 2, 3, 4]
random.shuffle(items)
print(items)
Example of infinite repetition until a condition is met:
while True:
answer = input("Type 'exit' to quit: ")
if answer == "exit":
break
Understanding loops, iterators, and repetition control — along with tools like `input`, `zip`, `enumerate`, and `shuffle` — empowers you to build flexible and intelligent programs. Loops are at the heart of many real-world algorithms, and mastering them makes your Python code truly dynamic.