# More on loops in Python

Previously, you explored iterative statements. An **iterative statement** is code that repeatedly executes a set of instructions. Depending on the criteria, iterative statements execute zero or more times. We iterated through code using both <var>for</var> loops and <var>while</var> loops. In this reading, you’ll recap the syntax of loops. Then, you'll learn how to use the <var>break</var> and <var>continue</var> keywords to control the execution of loops.

## for loops  

If you need to iterate through a specified sequence, you should use a <var>for</var> loop.

The following <var>for</var> loop iterates through a sequence of usernames. You can run it to observe the output:

```python
for i in ["elarson", "bmoreno", "tshah", "sgilmore"]:
    print(i)
```

Output

```
elarson
bmoreno
tshah
sgilmore
```

The first line of this code is the loop header. In the loop header, the keyword <var>for</var> signals the beginning of a <var>for</var> loop. Directly after <var>for</var>, the loop variable appears. The **loop variable** is a variable that is used to control the iterations of a loop. In <var>for</var> loops, the loop variable is part of the header. In this example, the loop variable is <var>i</var>.

The rest of the loop header indicates the sequence to iterate through. The <var>in</var> operator appears before the sequence to tell Python to run the loop for every item in the sequence. In this example, the sequence is the list of usernames. The loop header must end with a colon (<var>:</var>).

The second line of this example <var>for</var> loop is the loop body. The body of the <var>for</var> loop might consist of multiple lines of code. In the body, you indicate what the loop should do with each iteration. In this case, it's to <var>print(i)</var>, or in other words, to display the current value of the loop variable during that iteration of the loop. For Python to execute the code properly, the loop body must be indented further than the loop header.

**Note:** When used in a <var>for</var> loop, the <var>in</var> operator precedes the sequence that the <var>for</var> loop will iterate through. When used in a conditional statement, the <var>in</var> operator is used to evaluate whether an object is part of a sequence. The example <var>if "elarson" in \["tshah", "bmoreno", "elarson"\]</var> evaluates to <var>True</var> because <var>"elarson"</var> is part of the sequence following <var>in</var>.

## **Looping through a list**

Using <var>for</var> loops in Python allows you to easily iterate through lists, such as a list of computer assets. In the following <var>for</var> loop, <var>asset</var> is the loop variable and another variable, <var>computer\_assets</var>, is the sequence. The <var>computer\_assets</var> variable stores a list. This means that on the first iteration the value of <var>asset</var> will be the first element in that list, and on the second iteration, the value of <var>asset</var> will be the second element in that list. You can run the code to observe what it outputs:

```python
computer_assets = ["laptop1", "desktop20", "smartphone03"]
for asset in computer_assets:
    print(asset)
```

output

```
laptop1
desktop20
smartphone03
```

**Note:** It is also possible to loop through a string. This will return every character one by one. You can observe this by running the following code block that iterates through the string <var>"security"</var>:

```python
string = "security"
for character in string:
    print(character)
```

output

```
s
e
c
u
r
i
t
y
```

### **Using range()**

Another way to iterate through a <var>for</var> loop is based on a sequence of numbers, and this can be done with <var>range()</var>. The <var>range()</var> function generates a sequence of numbers. It accepts inputs for the start point, stop point, and increment in parentheses. For example, the following code indicates to start the sequence of numbers at <var>0</var>, stop at <var>5</var>, and increment each time by <var>1</var>:

<var>range(0, 5, 1)</var>

**Note:** The start point is inclusive, meaning that <var>0</var> will be included in the sequence of numbers, but the stop point is exclusive, meaning that <var>5</var> will be excluded from the sequence. It will conclude one integer before the stopping point.

When you run this code, you can observe how <var>5</var> is excluded from the sequence:

```python
for i in range(0, 5, 1):
    print(i)
```

output

```
0
1
2
3
4
```

You should be aware that it's always necessary to include the stop point, but if the start point is the default value of <var>0</var> and the increment is the default value of <var>1</var>, they don't have to be specified in the code. If you run this code, you will get the same results:

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

output

```
0
1
2
3
4
```

**Note:** this is the last time i put output under the code and above the output, asume if theres two code blocks next to eachother without a space that its teh output

**Note:** If the start point is anything other than <var>0</var> or the increment is anything other than <var>1</var>, they should be specified.

## while loops

If you want a loop to iterate based on a condition, you should use a <var>while</var> loop. As long as the condition is <var>True</var>, the loop continues, but when it evaluates to <var>False</var>, the <var>while</var> loop exits. The following <var>while</var> loop continues as long as the condition that <var>i &lt; 5</var> is <var>True</var>:

```python
i = 1
while i < 5:
    print(i)
    i = i + 1
```

```
1
2
3
4
```

In this <var>while</var> loop, the loop header is the line <var>while i &lt; 5:</var>. Unlike with <var>for</var> loops, the value of a loop variable used to control the iterations is not assigned within the loop header in a <var>while</var> loop. Instead, it is assigned outside of the loop. In this example, <var>i</var> is assigned a starting value of <var>1</var> in a line preceding the loop.

The keyword <var>while</var> signals the beginning of a <var>while</var> loop. After this, the loop header indicates the condition that determines when the loop terminates. This condition uses the same comparison operators as conditional statements. Like in a <var>for</var> loop, the header of a <var>while</var> loop must end with a colon (<var>:</var>).

The body of a <var>while</var> loop indicates the actions to take with each iteration. In this example, it is to display the value of <var>i</var> and to increment the value of <var>i</var> by <var>1</var>. In order for the value of <var>i</var> to change with each iteration, it's necessary to indicate this in the body of the <var>while</var> loop. In this example, the loop iterates four times until it reaches a value of <var>5</var>.

### Integers in the loop condition

Often, as just demonstrated, the loop condition is based on integer values. For example, you might want to allow a user to log in as long as they've logged in less than five times. Then, your loop variable, <var>login\_attempts</var>, can be initialized to <var>0</var>, incremented by <var>1</var> in the loop, and the loop condition can specify to iterate only when the variable is less than <var>5</var>. You can run the code below and review the count of each login attempt:

```python
login_attempts = 0
while login_attempts < 5:
    print("Login attempts:", login_attempts)
    login_attempts = login_attempts + 1
```

```
Login attempts: 0
Login attempts: 1
Login attempts: 2
Login attempts: 3
Login attempts: 4
```

The value of <var>login\_attempts</var> went from <var>0</var> to <var>4</var> before the loop condition evaluated to <var>False</var>. Therefore, the values of <var>0</var> through <var>4</var> print, and the value <var>5</var> does not print.

### Boolean values in the loop condition

Conditions in <var>while</var> loops can also depend on other data types, including comparisons of Boolean data. In Boolean data comparisons, your loop condition can check whether a loop variable equals a value like <var>True</var> or <var>False</var>. The loop iterates an indeterminate number of times until the Boolean condition is no longer <var>True</var>.

In the example below, a Boolean value is used to exit a loop when a user has made five login attempts. A variable called <var>count</var> keeps track of each login attempt and changes the <var>login\_status</var> variable to <var>False</var> when the <var>count</var> equals <var>4</var>. (Incrementing <var>count</var> from <var>0</var> to <var>4</var> represents five login attempts.) Because the <var>while</var> condition only iterates when <var>login\_status</var> is <var>True</var>, it will exit the loop. You can run this to explore this output:

```python
count = 0
login_status = True
while login_status == True:
    print("Try again.")
    count = count + 1
    if count == 4:
        login_status = False
```

```
Try again.
Try again.
Try again.
Try again.
```

The code prints a message to try again four times, but exits the loop once <var>login\_status</var> is set to <var>False</var>.

## Managing loops

You can use the <var>break</var> and <var>continue</var> keywords to further control your loop iterations. Both are incorporated into a conditional statement within the body of the loop. They can be inserted to execute when the condition in an <var>if</var> statement is <var>True</var>. The <var>break</var> keyword is used to break out of a loop. The <var>continue</var> keyword is used to skip an iteration and continue with the next one.

## **break**

When you want to exit a <var>for</var> or <var>while</var> loop based on a particular condition in an <var>if</var> statement being <var>True</var>, you can write a conditional statement in the body of the loop and write the keyword <var>break</var> in the body of the conditional.

The following example demonstrates this. The conditional statement with <var>break</var> instructs Python to exit the <var>for</var> loop if the value of the loop variable <var>asset</var> is equal to <var>"desktop20"</var>. On the second iteration, this condition evaluates to <var>True</var>. You can run this code to observe this in the output:

```python
computer_assets = ["laptop1", "desktop20", "smartphone03"]
for asset in computer_assets:
    if asset == "desktop20":
        break
    print(asset)
```

```
laptop1
```

As expected, the values of <var>"desktop20"</var> and <var>"smartphone03"</var> don't print because the loop breaks on the second iteration.

## **continue**

When you want to skip an iteration based on a certain condition in an <var>if</var> statement being <var>True</var>, you can add the keyword <var>continue</var> in the body of a conditional statement within the loop. In this example, <var>continue</var> will execute when the loop variable of <var>asset</var> is equal to <var>"desktop20"</var>. You can run this code to observe how this output differs from the previous example with <var>break</var>:

```python
computer_assets = ["laptop1", "desktop20", "smartphone03"]
for asset in computer_assets:
    if asset == "desktop20":
        continue
    print(asset)
```

```
laptop1
smartphone03
```

The value <var>"desktop20"</var> in the second iteration doesn't print. However, in this case, the loop continues to the next iteration, and <var>"smartphone03"</var> is printed.

## Infinite loops

If you create a loop that doesn't exit, this is called an infinite loop. In these cases, you should press <var>CTRL-C</var> or <var>CTRL-Z</var> on your keyboard to stop the infinite loop. You might need to do this when running a service that constantly processes data, such as a web server.

## Key takeaways

Security analysts need to be familiar with iterative statements. They can use <var>for</var> loops to perform tasks that involve iterating through lists a predetermined number of times. They can also use <var>while</var> loops to perform tasks based on certain conditions evaluating to <var>True</var>. The <var>break</var> and <var>continue</var> keywords are used in iterative statements to control the flow of loops based on additional conditions.