Back to Blog

Learn Python Loops in 6 Minutes - for, while, range(), enumerate() | Tutorial #7

Sandy LaneSandy Lane

Video: Learn Python Loops in 6 Minutes - for, while, range(), enumerate() | Tutorial #7 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Learn Python Loops: for, while, range(), and enumerate()

Loops are fundamental in Python for repeating tasks efficiently. This tutorial covers for loops using range() for counting, iterating over lists, and enhancing loops with enumerate() and zip(). It also explains while loops with control statements like break and continue, plus the less-known else clause on loops.

Code

# For loop with range() to print numbers 0 to 4
for i in range(5):
  print("Count:", i)

# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
  print("Fruit:", fruit)

# Using enumerate() to get index and value
for index, fruit in enumerate(fruits):
  print(f"Index {index}: {fruit}")

# Using zip() to iterate over two lists simultaneously
colors = ["red", "yellow", "dark red"]
for fruit, color in zip(fruits, colors):
  print(f"{fruit} is {color}")

# While loop with break and continue
count = 0
while count < 10:
  count += 1
  if count == 3:
    continue  # Skip printing 3
  if count == 7:
    break     # Exit loop when count is 7
  print("Count in while:", count)
else:
  print("Loop ended without break")

# Mini Project: Number Guessing Game
import random
secret = random.randint(1, 10)
while True:
  guess = int(input("Guess a number between 1 and 10: "))
  if guess == secret:
    print("You guessed it!")
    break
  elif guess < secret:
    print("Too low, try again.")
  else:
    print("Too high, try again.")

Key Points

  • for loops iterate over sequences like lists or ranges for controlled repetition.
  • enumerate() adds counters to loops, providing index and value simultaneously.
  • zip() allows parallel iteration over multiple sequences.
  • while loops repeat based on a condition, with break and continue controlling flow.
  • Loops can have an else clause that runs if the loop completes without hitting a break.