> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Loops Automation

> Intro to Python loops explaining for and while usage, range, break and continue, iterating iterables, avoiding infinite loops, and automation examples.

Welcome back.

Your code can already store information and make decisions. Loops let that code repeat actions reliably — whether ten times or a thousand — without duplicating statements. In this lesson you'll learn how to use Python loops for automation, when to choose `for` vs `while`, and how to control loop flow.

In this lesson you will learn to:

* Use `for` loops to repeat an action a fixed number of times or iterate over collections.
* Use `while` loops to repeat until a condition changes.
* Track and update variables inside loops and use `break` to exit early.
* Decide when to use `for` versus `while` loops in automation tasks.

Why loops matter

* Reduce repetition and human error.
* Make code scalable and easier to maintain.
* Combine with data structures (lists, dicts, files) to process many items automatically.

Create a new file named `loops.py`.

For loops — repeat a fixed number of times
Without loops you would have to repeat statements manually. For example, printing numbers 0–10 with no loop would be tedious. A `for` loop does it succinctly:

```python theme={null}
# loops.py
# Print numbers 0 through 10
for i in range(11):
    print(i)
```

Quick breakdown:

* `for` and `in` define the loop header.
* `i` is the loop variable (conventionally `i`, but any name works).
* `range(11)` produces numbers from 0 up to, but not including, 11.
* `print(i)` runs each iteration.

<Callout icon="lightbulb" color="#1CB2FE">
  In many programming languages, counting often starts at zero. `range(n)` produces 0 through n-1 — this zero-based indexing aligns with arrays, lists, and memory layouts. Use `range(start, stop, step)` when you need custom start, end, or step values.
</Callout>

range(start, stop, step) options

| Variant | What it produces | Example |
| - | - | - |
| `range(stop)` | 0 up to `stop - 1` | `range(5)` → `0,1,2,3,4` |
| `range(start, stop)` | `start` up to `stop - 1` | `range(1, 6)` → `1,2,3,4,5` |
| `range(start, stop, step)` | `start` to `stop - 1`, stepping by `step` | `range(1, 11, 2)` → `1,3,5,7,9` |

Example: simple ranges

```python theme={null}
# start at 1, stop before 11 (1..10)
for i in range(1, 11):
    print(i)

# start at 1, stop before 11, step by 2 (odd numbers 1..9)
for i in range(1, 11, 2):
    print(i)
```

Countdown (reverse range) with a pause between iterations
To add a delay between loop iterations, import the `time` module and use `time.sleep()`:

```python theme={null}
import time

print("T-minus:")
for i in range(10, 0, -1):  # 10 down to 1
    print(i)
    time.sleep(1)
print("Lift off! 🚀")
```

Multiplication table example
Loops can do calculations each iteration. This example asks the user which times table to show and prints 1 through 10:

```python theme={null}
number = int(input("Which times table? "))

for i in range(1, 11):
    result = number * i
    print(f"{number} x {i} = {result}")
```

Example run (user enters `5`):

```text theme={null}
Which times table? 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
```

Iterating over other iterables
`for` loops work with many iterable types: lists, tuples, strings, dictionaries, file objects, and generator expressions. A couple of quick examples:

```python theme={null}
# iterate over a list
names = ["Alice", "Bob", "Charlie"]
for name in names:
    print(name)

# iterate over characters in a string
for ch in "python":
    print(ch)

# iterate over dictionary keys and values
scores = {"alice": 90, "bob": 82}
for name, score in scores.items():
    print(f"{name} -> {score}")
```

While loops — repeat until a condition changes
Use a `while` loop when you don't know how many iterations are required in advance — for example, waiting for valid user input or monitoring an external condition.

Basic structure:

```python theme={null}
while condition:
    # body runs while condition is True
```

Password example:

```python theme={null}
password = "python"

while True:
    guess = input("Enter password: ")
    if guess == password:
        print("Correct, welcome!")
        break
    else:
        print("Wrong, try again!")
```

Explanation:

* `while True:` creates a loop that repeats until `break` is executed.
* Each iteration asks the user for input. When the guess matches `password`, `break` exits the loop; otherwise it repeats.

<Callout icon="warning" color="#FF6B6B">
  Be careful with `while` loops — if the condition never becomes false (or you never `break`), the program runs forever. Ensure the loop updates state or receives input that can end the loop to avoid infinite loops.
</Callout>

Mood example
A similar `while` pattern that accepts only "happy" or "sad":

```python theme={null}
while True:
    mood = input("How do you feel today? (happy/sad): ").strip().lower()
    if mood == "happy":
        print("Wonderful — keep smiling!")
        break
    elif mood == "sad":
        print("Oh dear — chin up.")
        break
    else:
        print("Please enter 'happy' or 'sad' only.")
```

Controlling loop flow: break and continue

* `break` exits the nearest loop immediately.
* `continue` skips the rest of the current iteration and proceeds to the next one.

Example:

```python theme={null}
for i in range(1, 11):
    if i == 5:
        continue  # skip printing 5
    if i == 9:
        break     # stop the loop at 9
    print(i)
```

Common mistakes and tips

| Mistake | Symptom | Fix |
| - | - | - |
| Missing colon (`:`) or wrong indentation | SyntaxError or logic not running | Add `:` and ensure proper indentation for blocks |
| Infinite `while` loop | Program appears to hang | Ensure the loop condition can change, use `break`, or add input/state updates |
| Off-by-one with `range()` | Unexpected number of iterations | Remember `range(stop)` excludes `stop`; use `range(start, stop+1)` if you need inclusive end |
| Not handling user input | Exceptions on invalid input | Validate and sanitize input; use `try`/`except` for conversions |

Recap

* Use `for` loops when you know the number of iterations or are iterating over a collection.
* Use `while` loops when the repetition depends on external state or user input.
* Loops can update variables, perform calculations, and use `break`/`continue` for finer control.
* Combine loops with data structures (lists, dictionaries, files) to build powerful automation patterns.

Next steps
You can store multiple items in lists and use loops with those lists to supercharge dashboards, goal trackers, and automated scripts — we'll cover lists and more advanced iteration techniques next.

Links and references

* [Python for loops — official docs](https://docs.python.org/3/tutorial/controlflow.html#for-statements)
* [Python while loops — official docs](https://docs.python.org/3/tutorial/controlflow.html#while-statements)
* [Python range() — official docs](https://docs.python.org/3/library/functions.html#func-range)

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/programming-fundamentals/module/b7e10a6f-82c0-4b55-a099-66ea1a6d06d4/lesson/89067a9e-0f9c-4698-91b3-78a5162893ee" />

  <Card title="Practice Lab" icon="flask-conical" cta="Learn more" href="https://learn.kodekloud.com/user/courses/programming-fundamentals/module/b7e10a6f-82c0-4b55-a099-66ea1a6d06d4/lesson/b4bc22f7-feaf-43ff-8d7e-5b05c5d40abc" />
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.