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
for item in sequence:
# do something
While-loop
while condition:
# do something and update the condition
Choosing the Right Loop
for
= fixed number of stepswhile
= 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).