PYW.png 4a: Loops II

Table of Contents

🎉Table of contents with working links🎉

1. Last time

1.1. For loops


1.2. Range


1.3. Updating variables in a loop


2. Reviewing exercises

Any difficulties?

3. Picking up where we left things

3.1. Nested for loops

Just like we have seen nested if statements…


… we can have nested for loops:


3.2. While loops

  • for: Iterate a predefined number of times.
    • This is also known as a definite iteration.
  • while: Keep on iterating until the condition is false.
    • This is known as an indefinite iteration.
count = 0
while count < 100:
    count += 1
    print(count)

In this example, I do not know how often it will run before it hits 100.

import random
import time
num = 0
while num < 100:
    add = random.randint(-1,1)
    num += add
    print(num-add, "+", add, "=", num)
    #time.sleep(1)

3.3. Control statements in loops

3.3.1. Break

Sometimes you want a for loop to stop when it encounters a particular condition.

You can use break for this.

count = 0
for i in "programming your world":
    if i == "r":
        count += 1
    elif i == "w":
        break
print(count)

An often used trick: start the while loop, and use break to define the conditions for the loop to end.

import random
import time
num = 0
while True:
    if input("Write something: ") == "exit":
        print("end")
        break

3.3.2. Continue

When the continue statement is executed, it skips the rest of the current iteration and moves on to the next iteration of the loop:

for i in range(5):
    if i == 2:
        continue
    print(i)

Created: 2025-03-03 ma 23:53