Learn Python: The Fundamentals

Loops are one of the most powerful tools in Python. They let you repeat blocks of code without writing them out multiple times. You’ll typically use:

 

  • for loops — when you want to go through items in a sequence (like a list or range)
  • while loops — when you want to repeat something until a condition is no longer true

 

You can also use break to stop a loop early or continue to skip just one iteration. And always make sure your while loop eventually stops — or you’ll be stuck in an infinite loop!

 

For and While in Action

Let’s see both types of loops in action:

 

# A for-loop that skips 4 and stops before 6
for i in range(1, 7):
    if i == 4:
        continue   # skip number 4
    if i == 6:
        break      # stop when i hits 6 (won’t print 6)
    print(i)

# A while-loop countdown
count = 5
while count > 0:
    print("T-minus", count)
    count -= 1

print("Lift-off!")

 

Common Loop Patterns

Want to loop through a set of numbers? Use range(start, stop, step).

 

Want to filter certain values? Use continue to skip them cleanly.

 

# Collect only the odd numbers from 1 to 10
odds = []
for n in range(1, 11):
    if n % 2 == 0:
        continue   # skip even numbers
    odds.append(n)

print(odds)  # [1, 3, 5, 7, 9]

 

Interactive Exercise: Countdown with Skip

Let’s build a countdown, but skip one specific number. Change the start and skip values to see how the output changes.

 


start = 10
skip = 7

while start > 0:
if start == skip:
start -= 1
continue
print(start)
start -= 1

# Try: start = 6, skip = 3

 
Make sure start -= 1 runs in both paths — otherwise you’ll end up in an infinite loop!
 

Loops are all about repetition and control. With for, while, break, and continue, you’ll be able to handle all kinds of tasks — from countdowns to data filtering and more.