while
loop to implement repeating tasks.True
.
count = 1
while count <= 5:
print(count)
count += 1
for
loop construct.for
.range()
to generate sequences.
for item in container:
# process item
roster = ["Alice", "Bob", "Carol"]
for student in roster:
print(student)
range()
for i in range(3): # 0,1,2
print(i)
for j in range(2, 5): # 2,3,4
print(j)
for k in range(1, 10, 3): # 1,4,7
print(k)
range()
supports start, stop, step.while
loops.for
loops.
x = 1
while x <= 2:
y = 1
while y <= 3:
print(x, y)
y += 1
x += 1
courses = [["Alice", "Bob"], ["Carol", "Dan"]]
for course in courses:
for student in course:
print(student)
break
and continue
to control iteration.break
— exit loop early
while True:
s = input("Enter 'q' to quit: ")
if s == "q":
break
print("You entered:", s)
break
(video)continue
— skip to next turn
for i in range(5):
if i == 2:
continue
print(i)
continue
(video)break
ends the loop immediately.continue
skips to the next iteration.else
clause to handle “no break” cases.for
or while
loops.else
runs only if the loop **did not** encounter a break
.
nums = [1, 2, 3, 4]
for n in nums:
if n == 10:
print("Found 10!")
break
else:
print("10 not found")