Python: A Guide to For and While Loops
Tags: python, beginners, programming
Published: 2024-02-20 22:57:38

# Introduction

In this chapter, we'll explore the use of for and while loops in Python. We'll start by showing how to create a loop using the `range` function, which allows us to iterate over a sequence of numbers. For example, we can use `range` to create a loop that prints the numbers 1 to 10:

```{python}
for i in range(1, 11):
    print(i)
```

```
Output:
1
2
3
4
5
6
7
8
9
10
```

# Using Range with Specific Intervals

We can also use `range` to create a loop that iterates over a specific interval, such as every other number between 1 and 10:

```{python}
for i in range(1, 11, 2):
    print(i)
```

```
Output:
1
3
5
7
9
```

# Using the Underscore as a Placeholder Variable

In Python, we can use an underscore (`_`) as a placeholder variable when we don't need the value of the variable in the loop. For example, if we want to repeat an action 5 times, we can use a for loop with an underscore as the loop variable:

```{python}
for _ in range(5):
    print("Exploring the universe!")
```

```
Output:
Exploring the universe!
Exploring the universe!
Exploring the universe!
Exploring the universe!
Exploring the universe!
```

# Iterating Through a List

We can also use a for loop to iterate through a list. For example, let's say we have a list of numbers, and we want to calculate the sum of these numbers:

```{python}
numbers = [1, 2, 3, 4, 5]
total = 0
for number in numbers:
    total += number
print(total)
```

```
Output:
15
```

# Using the Else Statement in a For Loop

We can use the `else` statement in a for loop to specify a block of code to be executed when the loop has finished iterating. For example, let's say we want to search for a specific number in our list of numbers, and print a message when we find it:

```{python}
numbers = [1, 2, 3, 4, 5]
for number in numbers:
    if number == 6:
        print("Number found!")
        break
else:
    print("Number not found!")
```

```
Output:
Number not found!
```

In this example, the `else` block is executed because the `break` statement is never reached, meaning that the loop completed all iterations without finding the number 6.

# Using the Break Statement

We can use the `break` statement to exit a loop prematurely. For example, let's say we want to search for the first even number in our list of numbers:

```{python}
numbers = [1, 2, 3, 4, 5]
for number in numbers:
    if number % 2 == 0:
        print(number)
        break
```

```
Output:
2
```

In this example, the `break` statement is used to exit the loop as soon as the first even number is found.

# Using the Enumerate Function

We can use the `enumerate` function to iterate through a list and keep track of the index of each element. For example, let's say we want to print the index and value of each number in our list:

```{python}
numbers = [1, 2, 3, 4, 5]
for i, number in enumerate(numbers):
    print(i, number)
```

```
Output:
0 1
1 2
2 3
3 4
4 5
```

# Using the Zip Function

We can use the `zip` function to iterate over two or more lists in parallel. For example, let's say we have two lists, one containing the names of shapes and another containing their areas, and we want to print the name and area of each shape:

```{python}
shapes = ["Circle", "Square", "Rectangle", "Triangle"]
areas = [3.14, 4, 6, 4.5]
for shape, area in zip(shapes, areas):
    print(f"{shape}: {area}")
```

```
Output:
Circle: 3.14
Square: 4
Rectangle: 6
Triangle: 4.5
```

# Using List Comprehension

List comprehension is a concise way to create lists. For example, let's say we want to create a list of the squares of the numbers from 1 to 10:

```{python}
squares = [x**2 for x in range(1, 11)]
print(squares)
```

```
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
```

# Using While Loops

We can also use a while loop to iterate while a certain condition is true. For example, let's say we want to calculate the factorial of a number using a while loop:

```{python}
n = 5
factorial = 1
while n > 1:
    factorial *= n
    n -= 1
print(factorial)
```

```
Output:
120
```

# Using the Walrus Operator

In Python 3.8, a new feature called the "walrus operator" (`:=`) was introduced, which allows us to assign values to variables as part of an expression. For example, let's say we want to calculate the factorial of a number using a while loop and the walrus operator:

```{python}
n = 5
factorial = 1
while (n := n - 1) > 0:
    factorial *= n + 1
print(factorial)
```

```
Output:
120
```

In this example, the walrus operator is used to decrement the value of `n` by 1 and assign the result back to `n` as part of the condition in the while loop.

# Conclusion

For and while loops are essential tools for controlling the flow of a program in Python. They provide a flexible and versatile way to iterate over sequences and repeat actions, allowing us to solve complex problems with ease.