LM Introduction

Loops let you repeat code without writing it multiple times. They help automate tasks, work with lists, and run code until a condition is met. Python has two main loop types: for and while.

  • Use a for-loop when you know how many times to repeat.
  • Use a while-loop when the number of repetitions depends on a condition.

For-loop

items = ["Python", "loops"]
for item in items:
  print(item)

While-loop

count = 1
while count <= 3:
  print(count)
  count += 1

Choosing the Right Loop

  • for = fixed number of steps
  • while = unknown number of steps

Examples

  • Iterate over a list → for
  • Repeat a task until a condition is met → while

Indentation

Python uses indentation to define blocks of code. Always indent consistently (e.g., 4 spaces).

Updated: