Class Coding Lab: Iterations

The goals of this lab are to help you to understand:

  • How loops work.
  • The difference between definite and indefinite loops, and when to use each.
  • How to build an indefinite loop with complex exit conditions.
  • How to create a program from a complex idea.

Understanding Iterations

Iterations permit us to repeat code until a Boolean expression is False. Iterations or loops allow us to write succinct, compact code. Here's an example, which counts to 3 before Blitzing the Quarterback in backyard American Football:


In [ ]:
i = 1
while i <= 3:
    print(i,"Mississippi...")
    i=i+1
print("Blitz!")

Breaking it down...

The while statement on line 2 starts the loop. The code indented beneath the while (lines 3-4) will repeat, in a linear fashion until the Boolean expression on line 2 i <= 3 is False, at which time the program continues with line 5.

Some Terminology

We call i <=3 the loop's exit condition. The variable i inside the exit condition is the only thing that we can change to make the exit condition False, therefore it is the loop control variable. On line 4 we change the loop control variable by adding one to it, this is called an increment.

Furthermore, we know how many times this loop will execute before it actually runs: 3. Even if we allowed the user to enter a number, and looped that many times, we would still know. We call this a definite loop. Whenever we iterate over a fixed number of values, regardless of whether those values are determined at run-time or not, we're using a definite loop.

If the loop control variable never forces the exit condition to be False, we have an infinite loop. As the name implies, an Infinite loop never ends and typically causes our computer to crash or lock up.


In [ ]:
## WARNING!!! INFINITE LOOP AHEAD
## IF YOU RUN THIS CODE YOU WILL NEED TO KILL YOUR BROWSER AND SHUT DOWN JUPYTER NOTEBOOK

i = 1
while i <= 3:
    print(i,"Mississippi...")
#    i=i+1
print("Blitz!")

For loops

To prevent an infinite loop when the loop is definite, we use the for statement. Here's the same program using for:


In [ ]:
for i in range(1,4):
    print(i,"Mississippi...")
print("Blitz!")

One confusing aspect of this loop is range(1,4) why does this loop from 1 to 3? Why not 1 to 4? Well it has to do with the fact that computers start counting at zero. The easier way to understand it is if you subtract the two numbers you get the number of times it will loop. So for example, 4-1 == 3.

Now Try It

In the space below, Re-Write the above program to count from 10 to 15. Note: How many times will that loop?


In [ ]:
# TODO Write code here

Indefinite loops

With indefinite loops we do not know how many times the program will execute. This is typically based on user action, and therefore our loop is subject to the whims of whoever interacts with it. Most applications like spreadsheets, photo editors, and games use indefinite loops. They'll run on your computer, seemingly forever, until you choose to quit the application.

The classic indefinite loop pattern involves getting input from the user inside the loop. We then inspect the input and based on that input we might exit the loop. Here's an example:


In [ ]:
name = ""
while name != 'mike':
    name = input("Say my name! : ")
    print("Nope, my name is not %s! " %(name))

The classic problem with indefinite loops is that its really difficult to get the application's logic to line up with the exit condition. For example we need to set name = "" in line 1 so that line 2 starts out as True. Also we have this wonky logic where when we say 'mike' it still prints Nope, my name is not mike! before exiting.

Break statement

The solution to this problem is to use the break statement. break tells Python to exit the loop immediately. We then re-structure all of our indefinite loops to look like this:

while True:
    if exit-condition:
        break

Here's our program we-written with the break statement. This is the recommended way to write indefinite loops in this course.

NOTE: We always check for the setinal value immediately after the input() function.


In [ ]:
while True:
    name = input("Say my name!: ")
    if name == 'mike':
        break
    print("Nope, my name is not %s!" %(name))

Multiple exit conditions

This indefinite loop pattern makes it easy to add additional exit conditions. For example, here's the program again, but it now stops when you say my name or type in 3 wrong names. Make sure to run this program a couple of times. First enter mike to exit the program, next enter the wrong name 3 times.


In [ ]:
times = 0
while True:
    name = input("Say my name!: ")
    times = times + 1
    if name == 'mike':
        print("You got it!")
        break
    if times == 3:
        print("Game over. Too many tries!")
        break
    print("Nope, my name is not %s!" %(name))

Number sums

Let's conclude the lab with you writing your own program which uses an indefinite loop.

We'll provide the to-do list, you write the code. This program should ask for floating point numbers as input and stops looping when the total of the numbers entered is over 100, or 5 numbers have been entered. Those are your two exit conditions. After the loop stops print out the total of the numbers entered and the count of numbers entered.


In [ ]:
## TO-DO List

#1   count = 0
#2   total = 0
#3   loop Indefinitely
#4.     input a number
#5      increment count
#6      add number to total
#7      if count equals 5 stop looping
#8      if total greater than 100 stop looping
#9 print total and count

In [ ]:
# TODO Write Code here:

Metacognition

Please answer the following questions. This should be a personal narrative, in your own voice. Answer the questions by double clicking on the question and placing your answer next to the Answer: prompt.

Questions

  1. Record any questions you have about this lab that you would like to ask in recitation. It is expected you will have questions if you did not complete the code sections correctly. Learning how to articulate what you do not understand is an important skill of critical thinking.

Answer:

  1. What was the most difficult aspect of completing this lab? Least difficult?

Answer:

  1. What aspects of this lab do you find most valuable? Least valuable?

Answer:

  1. Rate your comfort level with this week's material so far.

1 ==> I can do this on my own and explain how to do it.
2 ==> I can do this on my own without any help.
3 ==> I can do this with help or guidance from others. If you choose this level please list those who helped you.
4 ==> I don't understand this at all yet and need extra help. If you choose this please try to articulate that which you do not understand.

Answer:


In [ ]:
# SAVE YOUR WORK FIRST! CTRL+S
# RUN THIS CODE CELL TO TURN IN YOUR WORK!
from ist256.submission import Submission
Submission().submit()