Iteration Statements
CSCI 1470

by K. Yue

1. Iteration: for loop

Example in Java:

for (int i = 0; i < 10; i++) { // Iterates from 0 to 9     System.out.println(i); }

  1. Initialization: int i = 0; Set the variable i = 0.
  2. Continuing condition: i < 10; so long as i is less than 10.
  3. Iteration code: what logic demands. E.g., System.out.println(i);
  4. Update code: i++ Increment i by 1

Example in Python:

for i in range(10): # Iterates from 0 to 9     print(i)

  1. Initialization: i is set to 0 implicitly. This is because the lower limit of range(10) is 0.
  2. Continuing condition: i < 10. This is because the lower limit of range(10) is 10.
  3. Iteration code: what logic demands. E.g., print(i);
  4. Update code: i is implicitly incremented by 1.

Tools:

bk.py:

This is a simple Python module that supports one function break_and_show(). When the function is called, it represents a break point. It shows the old and new values of all variables that have been changed. It contains many limitations.

To use the module, put bk.py in your working project directory and add the following line in your python program:

from bk import break_and_show

Format:

for iteration_variable in iterable_object:      # A block of iteration code to be executed.      # Indentation is required as the block is one level lower.

Examples:

Try the following three python programs on for loops.

for_1.py:

from bk import break_and_show
debug = False    # set debug to False if you do not want to see breakpoints.

#  Version 1: loop five times from 0 to 4.
for i in range(5):      # range(stop): start assumes to be 0.
    if debug: break_and_show()
    print(f"square({i}): {i * i}")

#  Version 2: loop five times from 1 to 5.
for i in range(1, 6):  # range(start, stop)
    if debug: break_and_show()
    print(f"square({i}): {i * i}")

#  Version 3: loop three times: 1, 3, 5.
for i in range(1, 6, 2):  # range(start, stop, step)
    if debug: break_and_show()
    print(f"square({i}): {i * i}")

# summing a list:
list_1 = [3,4,1,7,8,3,6]
print(f"list_1: {list_1}")
print(f"len(list_1): {len(list_1)}")

list_sum = 0
for i in range(len(list_1)):
    if debug: break_and_show()
    list_sum += list_1[i]
print(f"sum of list_1: {list_sum}")
print(f"sum(list_1): {sum(list_1)}")

for_2.py:

from bk import break_and_show
debug = False    # set debug to False if you do not want to see breakpoints.

data_points = [10, 25, 30, 15, 40]
for point in data_points:
    if debug: break_and_show()
    print(f"Data point: {point}")
   
my_string = "love"
for char in my_string:
    if debug: break_and_show()
    print(char)

numbers = [11, 22, 33, 44, 55]
total_sum = 0
for num in numbers:
    total_sum += num
    if debug: break_and_show()
print(f"Total sum: {total_sum}")

for_3.py:

from bk import break_and_show
debug = True    # set debug to False if you do not want to see breakpoints.

raw_scores = [25, 82, 58, 98]
scaled_scores = []
i = 1
for score in raw_scores:
    scaled_scores.append(score / 100)
    i += 1
    if debug: break_and_show()
print(f"Scaled scores: {scaled_scores}") 

2. while loop

Format:

while condition:
    # Code to be executed repeatedly
    # Indentation is required for the block.

Recall that there are four components of a loop statement.

  1. Initialization: preparatory logic before entering the loop. To be executed once.
  2. Continuing condition: when the loop should be exit.
  3. Iteration code: a block of code to be executed. To be executed as many times as the loop continues.
  4. Update code: update the variables involved in the continuing condition to prepare whether the loop should continues.

Thus, the general structure of a while loop:

# [1] initialization code
while condition: # [2] continuing condition.
    # Code to be executed repeatedly: [3] Iteration code
    # [4] Update code is usually at the end of the while block

Examples: loop five times from 1 to 5.

Using for loop:

#  loop five times from 1 to 5 using for loop and range function
for i in range(1, 6):  # range(start, stop)
    if debug: break_and_show()
    print(f"square({i}): {i * i}")

Using while loop: while_1.py

#  loop five times from 1 to 5 using while loop
i = 1
while i < 6:
    if debug: break_and_show()
    print(f"square({i}): {i * i}")
    i += 1

while_2.py: simple while loops and how to improve them.

from bk import break_and_show
debug = True    # set debug to False if you do not want to see breakpoints.
  
#   version #1
required_samples = 3
collected_samples = 0
data_points = []

while collected_samples < required_samples:
    data_input = input(f"Enter data point {collected_samples + 1}/{required_samples}: ")
    data_points.append(data_input)
    collected_samples += 1
    print(f"Data point '{data_input}' recorded.")

print("\nAll required data samples collected:")
for data in data_points:
    print(f"Sample: {data}")
   
 
#   version #2
required_samples = 3
data_points = []

while len(data_points) < required_samples:
    data_input = input(f"Enter data point {len(data_points) + 1}/{required_samples}: ")
    data_points.append(data_input)
    print(f"Data point '{data_input}' recorded.")

#   Also print sample #.
print("\nAll required data samples collected:")
i = 0
while i < len(data_points):
    print(f"Sample #{i+1}: {data_points[i]}")
    i += 1

#   Alternate solution using enumerate
print("\nAll required data samples collected:")
for i, data in enumerate(data_points):
    print(f"Sample {i+1}: {data}")

while_yes_no.py: a simple use case of getting a yes or no user input and why a function is defined.

def get_yes_no_input(prompt_message):
    """
    Prompts the user for a yes/no input and returns True for yes, False for no.
    Handles variations like 'y', 'yes', 'n', 'no' (case-insensitive).
    """
    while True:
        user_input = input(f"{prompt_message} (yes/no): ").lower().strip()      # conver to lower case and remove trailing white spaces.
        if user_input in ('yes', 'y'):
            return True
        elif user_input in ('no', 'n'):
            return False
        else:
            print("Invalid input. Please enter 'yes' or 'no'.")

# Example usage:
if get_yes_no_input("Do you want to continue?"):
    print("Good. Here is another question.")
else:
    print("User chose to stop.")

answer = get_yes_no_input("Is life a box of chocolate?")
if answer:
    print("Great!")
else:
    print("Then, get pizza.")

 

Fibonacci numbers: 0,1,1,2,3,5,8,13,21,

fib(1) = 0
fib(2) = 1
fib(n) = fib(n-1) + fib(n-2)

for_fib_1.py: print the first 20 Fibonacci numbers

# Initialize the first two Fibonacci numbers
a, b = 0, 1

# Print the first two numbers
print(a)
print(b)

# Loop to calculate and print the remaining 18 Fibonacci numbers
for _ in range(18):  # We need 18 more numbers after the initial two
    next_fib = a + b
    print(next_fib)
    a = b
    b = next_fib
 

while_fib_1.py: print all Fibonacci numbers smaller than 50,000.

LIMIT = 50000

# Initialize the first two Fibonacci numbers
a, b = 0, 1

# Print the starting number 0, since it is less than the limit
print(a)

# Use a while loop to generate and print the sequence
while b < LIMIT:
    print(b)
    # Update the values for the next iteration
    # The new 'a' becomes the old 'b', and the new 'b' is their sum
    a, b = b, a + b

while_valid_number.py:

# input validation
while True:
    try:
        user_input = input("Please enter an integer: ")
        number = int(user_input)
        break  # Exit the loop if input is a valid integer
    except ValueError:
        print(f"Not an integer: {user_input}. Pleas try again.  ")

print(f"You entered the number: {number}")

 

while_nested_1.py: what is the output of this code?

i = 1
while i <= 3:
    j = 1
    while j <= i:
        print(f"Outer loop variable, i: {i}, Inner loop variable, j: {j}")
        j += 1
    i += 1