Loops in Python

Programming Fundamentals October 15, 2025

Loops in Python


For Loop

  • Used to iterate over sequences (list, string, range).
for i in range(1, 6):
    print(i)

Iterating lists and strings:

for name in ['Ali', 'Sara', 'John']:
    print(name)

for c in 'Python':
    print(c)

For loop with else:

for i in range(3):
    print(i)
else:
    print('Loop Finished!')

While Loop

  • Repeats as long as the condition is true.
i = 1
while i < 6:
    print(i)
    i += 1

Break Statement:

i = 1
while i < 6:
    if i == 3:
        break
    print(i)
    i += 1

Continue Statement:

i = 0
while i < 6:
    i += 1
    if i == 3:
        continue
    print(i)

Else in While:

i = 1
while i <= 5:
    print(i)
    i += 1
else:
    print('Done!')

User Input Loop:

sum = 0
num = int(input('Enter number (0 to stop): '))
while num != 0:
    sum += num
    num = int(input('Enter number (0 to stop): '))
print('Total:', sum)

Infinite Loops

while True:
    print('Running...')
    if input('Type STOP to exit: ') == 'STOP':
        break

Loop Summary

LoopUsed ForKeywords
forIterating over sequencesrange(), list, string
whileRepeating until condition falsebreak, continue, else

Key Takeaways

  • For loops iterate over items in a sequence.
  • While loops run until a condition becomes False.
  • Use break to exit a loop early.
  • Use continue to skip an iteration.
  • else executes after loops finish normally.