---
# System prepended metadata

title: 11-25 Loops
tags: [Unit 5 - Loops]

---

# Repetition statements

-   Natural and computer languages can describe things that are repeated.

> "For the LORD is good and his love endures forever; his faithfulness continues through all generations." Psalm 100?5

-   In computer science, repetition is portrayed with the metaphor of a loop.

> One aspect of the LOOP, and in many ways its defining quality, is the minimal means that result in automated infinite production. Is it when writing a simple FOR statement for the first time, counting to, say, 10 and printing to the screen at each iteration, that the novice programmer “Beheld the living traces and the sky-pointing proportions of the mighty Pan”?
- Wilfried Hou Je Bek, "Loops", in "Software studies: a lexicon"

### How do we rule with loops?

-   Every time we use a loop, we are pronouncing a judgment about **what similar and what is different**.
-   Every time we use a loop, we are pronouncing a judgment about **what can be scaled**.

## Two types of loops

1. **Definite iteration**: Loops that repeat a predefined number of times - the FOR statement
2. **Indefinite iteration**: Loops that continue until a condition occurs - the WHILE statement
    
> "Although often interchangeable, FOR is like a tourist that knows when it will 
be home (but with the power to RETURN earlier), WHILE is like a traveller 
away for as long as there is no hard reason to come back, potentially forever."
- Wilfried Hou Je Bek, "Loops", in "Software studies: a lexicon"

# Infinite loops

-   If a loop termination condition is never met, we have an "infinite loop"

```python
count = 0
while (count < 9):
   print('The count is:', count)
print("Good bye!")
```

-   In this case, notice we didn't update the **counting variable**
    (also called **iterator** or **loop variable**)

# Nested loops

Loops can also be placed inside of loops.

```python
for x in range(5):
    print(x, end=' ')
    for y in range(x,4):
        print(y, end=' ')
    print()
```

*You can visualize this code at [http://www.pythontutor.com/visualize.html](http://www.pythontutor.com/visualize.html)*

What will this print?

# Break and continue

-   A `break` statement in a loop causes an immediate exit of the loop.

```python
sum = 0.0
while True:
    data = input('Enter a number: ')
    if data == '':
        break
    sum += float(data)
print('The sum is', sum)
```

-   A `continue` statement causes the loop to go to the next iteration immediately.

```python
for number in range(1, 11):  # Loop through numbers 1 to 10
    if number % 2 == 0:  # Check if the number is even
        continue  # Skip the rest of the loop for even numbers
    print(number)  # Print the number if it's odd
```

# List comprehensions

Python offers a shorter syntax when you want to create a new list based on the values of an existing sequence.

For example:
```python
names = ["Anakin", "Luke", "Leia"]
names_with_last_name = [ n+" Skywalker" for n in names]
print(names_with_last_name)
```

Using ranges: 
```python
length = 15
exponents2 = [ 2**i for i in range(length)]
print(exponents2)
```

Nesting comprehensions:
```python
w = 4
h = 4
zero_matrix = [ [0 for j in range(h)] for i in range(w)]
print(zero_matrix)
```

Checking conditions:

```python
x = [3, 6, -2, 5, -12, 5, -1]
only_positives = [i for i in x if i > 0]
print(only_positives)
```

```python
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
```

## Some exercises

**1. Convert Speed from km/h to m/s**

- We collected data in kilometers per hour (km/h), but we need to convert them to meters per second (m/s).
- You are given the following list of speeds in km/h:

```python
speeds_kmh = [50, 80, 120, 150, 180]
```

- Write a list comprehension to convert these speeds to m/s (use the conversion factor: 1 km/h = 0.27778 m/s).

**2. Filter and Square Positive Numbers**

- We are analyzing current measurements (in amperes) in an electric circuit. The data includes some negative numbers representing measurement errors.

- You are given the following list of current readings:

```python
currents = [-3.4, 5.0, -2.1, 7.8, -6.0, 3.3]
```

**3. Extract Odd-Length Strings**

- We got a list of building materials, and want to focus only on the materials with names of odd lengths.

- You are given the following list of materials:

```python
materials = ['concrete', 'wood', 'steel', 'glass', 'plastic', 'brick']
```

- Write a list comprehension to extract the materials whose names have an odd number of characters.

# Looping through dictionaries

- You can loop through keys:

```python
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key in my_dict:
    print(key)
```

- Or through values:

```python
for value in my_dict.values():
    print(value)
```

Or through key-value pairs:

```python
for key, value in my_dict.items():
    print(f"Key: {key}, Value: {value}")
```

## Dictionary comprehensions

```python
squared_numbers = {num: num**2 for num in range(1, 6)}
print(squared_numbers)
```

```python
inventory = {'apples': 50, 'bananas': 30, 'oranges': 75, 'grapes': 100}
low_stock = {item: qty for item, qty in inventory.items() if qty < 50}
print(low_stock)
```

```python
temperatures_celsius = {'Monday': 20, 'Tuesday': 22, 'Wednesday': 25}
temperatures_fahrenheit = {day: temp * 9/5 + 32
                           for day, temp in temperatures_celsius.items()} 
print(temperatures_fahrenheit)
```


# The Halting Problem

-   Is it possible to be sure that a program is not stuck?
-   Impressively, Alan Turing proved that NO! Computer programs are *undecidable*.

{{< video https://www.youtube.com/watch?v=92WHN-pAFCs >}}

## Discussion: what is enough?

-   In some sense, that means that there is not always an mathematical/algorithmic answer to the question: "is it enough?"

-   Maybe we can say that, as society gets more control over reality, nothing is enough. We enter in what sociologist Hartmut Rosa explored as an [**acceleration society**](https://www.amazon.com/Social-Acceleration-Modernity-Directions-Critical/dp/0231148356). We don't know any halt.

> "Pure activity does nothing more than prolong what already exists. (...) Activity that follows the stupidity of mechanics is poor in interruptions. Machines cannot pause. Despite all its computational performance, the computer is stupid, in that it lacks the ability to hesitate. (...) Possibly the computer counts faster than the human brain, and without repulsion welcomes an immensity of data, because it is free from any *alterity*. It is a positive machine. Precisely because of its autistic self-relation, because of the lack of nativity, the *idiot savant* generates those performances that only a computational machine would be capable of. In the thrust of that general positivation of the world, both man and society become a *machine of autistic performance*." - Byung-Chul Han, "The Burnout Society"

> "... our hearts are restless till they find rest in Thee." - Augustine of Hippo, *Confessions*