> For the complete documentation index, see [llms.txt](https://calnotes.gitbook.io/cs61a-guidebook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://calnotes.gitbook.io/cs61a-guidebook/building-blocks/control-flow/what-is-a-loop.md).

# What is a Loop?

While and For, among other things.

Say, we want to print "Hello!" 3 times. One might consider doing it like this:

```python
print("Hello!")
print("Hello!")
print("Hello!")
```

What if you wanted to print the same thing, say, a hundred times? It is clearly impractical to write this statement a hundred times. Instead, we'll use loops to execute this block of code.

This can be done through various different syntaxes. First, we introduce the for loop:

```python
for i in range(100):
    print("Hello!")
```

Next, we show how you can write the same piece of code using a while loop:

```python
i = 100
while i != 0:
    print("Hello!")
    i = i - 1
```

### The Anatomy of a Loop

A loop has four parts:

* **Initialization**: Setting up the initial, starting value for the variable that our loop uses.
* **Condition**: The condition statement, which stops the looping when it becomes false.
* **Execution** **Suite**: The code inside the loop that gets executed every time the loop runs.&#x20;
* **Updation**: Updating the looping variable to get us closer to making the condition false.&#x20;

We use the while loop to mark out these four sections.

```python
i = 100 # initialization
while i != 0: # condition
    print("Hello!") # execution suite
    i = i - 1 # updation
```

A for loop is similar, but with lots of this stuff hidden away behind the scenes. We iterate over the range, such that range is defined as `range(start=0, stop, step=1)` where our values start at `start` (inclusive), end at `stop` (exclusive) and proceed by `step`. As an example, `range(1, 5, 2)` would return the values 1 and 3. The default values for start and step are 0 and 1 respectively. Thus, something like&#x20;

```python
for i in range(10):
    print(i)
```

Prints out all the numbers from 1 to 9.

#### Difference between a for and a while loop

So when do we use a for loop and when do we use a while loop? There isn't any hard and fast rule, but the general rule of thumb is this: if we have a fixed number of times we want to loop over a piece of code, use a for loop. If the number of times we loop over something depends over a condition without a fixed number, use a while loop.

We'll attempt enough examples with both to get intuition about when to use which one!
