Module 8: Loops: the for loop | CMSC 105 Elementary Programming - Fall 2024

Module 8: Loops: the for loop

Note: Create a text file called module8.txt where you will store you answers to exercise questions. The questions that are not related to changing code. You will submit this file on Blackboard along with your code.

Objectives

By the end of this module you will be able to:

An example

for i in range(6):
    print(i)

Exercise 1: Type up the above in my_forloop_example.py and run it. You should observe this:

0
1
2
3
4
5

In the place in the code where you see the number 6, replace 6 with 10 and then run the program. Next, try 2 instead of 6. Finally, try 0 instead of 6. What is the output in each case? Report in your module text file (module8.txt). Submit the program with 6.


Let’s now examine elements of the loop:

Let’s change the program slightly and then set about explaining how the loop works:

for i in range(6):
    print(i)
    print('Hello')

Exercise 2: Type up the above in my_forloop_example2.py and run the program.


Observe that the body of this for-loop has two statements:

for i in range(6):
    print(i)           # Body line 1
    print('Hello')     # Body line 2

Let’s now use a slightly fictionalized way to explain the action of this loop:

Variations

To explore for-loops further, we’ll look at some variations of the basic for-loop:


Exercise 3: Type up the above four examples in my_forloop_variation1.py, my_forloop_variation2.py, my_forloop_variation3.py, and my_forloop_variation4.py. Run to confirm the output.


Exercise 4: In count_odd_up.py, write a loop to print the odd numbers from 1 to 25 (thus, skipping by 2, and including 1 and 25 in the output).


Exercise 5: In count_even_down.py, write a loop to print the even numbers from 24 down to 2 (inclusive of 24 and 2).


Nested for-loops

We’ll start by writing a program to print a little number triangle like this:

1
22
333
4444

Notice: there’s repetition across a row of numbers: a potential use of for-loops!

We’ll do this in stages, starting with this program:

print(1)               # print 1 all by itself

for i in range(2):     # i will start at 0, go up to 1
    print(2, end='')
print()                # Print nothing but go to the next line.

for i in range(3):     # i ranges from 0 to 2
    print(3, end='')
print()

for i in range(4):     # i ranges from 0 to 3
    print(4, end='')
print()

Observe:


Exercise 6: Add a row for 5 (with five of them), writing your code in my_forloop_print.py


Exercise 7: Just for the heck of it, could one use a for-loop to achieve the printing of 1 all by itself? That is, answer the question in your module8.txt: can a for-loop be set up so that you go into it exactly once? Write your code in my_forloop_print2.py


Next, observe that the upper-limits of the for-loops are themselves increasing:

print(1)               

for i in range(2):   # first loop has limit 2
    print(2, end='')
print()                

for i in range(3):   # second loop has limit 3
    print(3, end='')
print()

for i in range(4):   # third loop has limit 4
    print(4, end='')
print()

Also, observe that the very thing we’re printing across a row is the loop limit itself:

print(1)               

for i in range(2):   
    print(2, end='')   # print limit 2
print()                

for i in range(3):   
    print(3, end='')   # print limit 3
print()

for i in range(4):   
    print(4, end='')   # print limit 4
print()

Another way to say this:

  1. When the value is 2, print a row of two 2’s
  2. When the value is 3, print a row of three 3’s
  3. When the value is 4, print a row of four 4’s

Thus, we could try to do is:

for j in range(2, 5):   # let j iterate from 2 to 4
    # print j occurrences of j using a loop

But we already know how to print a row of j’s:

for j in range(2, 5):   # let j iterate from 2 to 4
    # print a row of j's (j of them)
    for i in range (j):
        print(j, end='')

Let’s put this together in a complete program:

print(1)                   # print 1 all by itself

for j in range(2, 5):      # j iterates from 2 to 4
    for i in range(j):     # for each j, print j of them
        print(j, end='')
    print()    

Exercise 8: Change the program to print a fifth row with five 5’s. Also adjust the for-loop so that the for-loop also takes care of printing the sole 1 that appears in the row of the sole 1’s. That is, adjust the for-loop conditions so that you don’t need the stand-alone print(1) to print 1. Write your code in my_forloop_print3.py


Let’s review what we learned above:

Tracing through a program in detail

We’ll now look at an example of how to execute a program “by hand”. That is, how to trace a program’s execution by painstakingly following its execution step-by-step.

At first this will appear tedious, but it is critical to a firm understanding of how programs execute, and eventually to your own writing of programs.

We’ll first do a longer, more narrative version here, and then show you how to submit a much shorter version for your exercises.

For our example, let’s look at the program we last saw:

print(1)                   

for j in range(2, 5):      
    for i in range(j):     
        print(j, end='')
    print()    

Exercise 9: Complete a tracing table of the program above and take a picture and save it as traceforloop.png and attach it to the Blackboard module 8 assignment.


Exercise 10: Write a program to print out consecutive integers in a diagonal, as in

  1
   2
    3
     4
      5

Use a nested for-loop as in earlier examples to print the requisite number of spaces before printing a digit. Write your code in my_diagonal_print.py


Exercise 11: Write a program to print out

I'm feeling cold: b rrrrrr rrrrr rrrr rrr rr r

Use a regular print to print everything up to the b. Then, use a nested for-loop for the r’s. Don’t forget the space between each grouping of r’s. Write your code in my_brr_print.py


When things go wrong

As code gets more complex, it gets easier to make mistakes, and harder to find them.

In each of the programs below, try to determine the error without compiling the program. Then, write up the program, compile and see what the compiler says. After that, fix the error.


Exercise 12:

for i in range(0 6):
    print(i)

Write your corrected code in my_loop_exercise1.py.


Exercise 13:

for i in range(0, 6)
    print(i)

Write your corrected code in my_loop_exercise2.py.


Exercise 14:

for i in range(0, 6:
    print(i)

Write your corrected code in my_loop_exercise3.py.


Exercise 15:

for i in range(0, 6):
print(i)

Write your corrected code in my_loop_exercise4.py.


Exercise 16:

for in range(0, 6):
    print(i)

Write your corrected code in my_loop_exercise5.py.


Exercise 17:

for i in range(0, 6):
    print i

Write your corrected code in my_loop_exercise6.py.


Let’s point out the difference between a syntax error and a logical error:


Exercise 18: The following code intends to print

55555
4444
333
22
1
for i in range(5, 0, 1):
    for j in range(1, i):
        print(i, end='')
    print()

But there are two bugs. First, try to find the problems solely by reading and mental execution. Then, type up the program in my_loop_exercise7.py. What does it print? Report what you see in module8.txt. Then fix the program to get the desired output.