Looping Using Runpython - Runpython-IntroProgramming/Course-Syllabus GitHub Wiki

Pete and Repeat are on a boat. Pete jumps out. Who is left on the boat?

Repeat

Pete and Repeat are on a boat. Pete jumps out. Who is left on the boat?

Repeat

Pete and Repeat are on a boat. Pete jumps out. Who is left on the boat?

Grr...

One of the powerful ideas in computer programming is that you can make one piece of code do the same thing over and over again. Write it once, then use it forever. This is where looping comes in.

But First

Do you remember the page on decision making? One thing that we glossed over is that a conditional statement actually evaluates to a single statement of True or False. In fact, True and False are built in Python objects that you can use any time you want a decision to be made 100% of the time. You can see this equivalence by playing with conditionals in Runpython Console:

>>> print(1==1)
True
>>> print(1==0)
False

This may come in handy below!

Shampoo, Rinse, Repeat

There are two common ways of repeating a piece of Python code over and over again. First up is the for statement. If you have written programs before using a language like C or Java, you might know what to expect with the for statement. Then again, you might not!

Suppose you want to come up with a method for calculating and printing the first ten perfect squares. That would be easy to do with a list comprehension:

>>> print([x**2 for x in range(2,12)])
[4, 9, 16, 25, 36, 49, 64, 81, 100, 121]

But suppose the repeating statement needed to be more complicated. What if it couldn't easily be expressed as a single statement, the way a list comprehension wants to see it? We could describe the calculation like this:

for each number n between 2 and 11
    print n squared

That is almost exactly the way Python would like to have you do it:

for i in range(2,12):
    print(i**2)

This code is similar to the if statement that you read about in the last lesson. Let's break it down. range(2,12) returns an iterator for generating a sequence of integers: 2,3,4,5,6,7,8,9,10,11.

for i in sets i equal to each of the numbers from the iterator, one after the other. Each time i is set to a new value from the iterator, Python executes all of the instructions in the indented block of code that follows. Once those instructions are finished, i is set to the next value from the iterator. When all of the values in the iterator have been used, the indented block is skipped and Python continues executing the code following the indented block.

And don't forget: if you need to indent a block of code, be sure the line above the block ends with a colon!

You can put as many lines of Python in the indented section as you need.

In this example, the indented code is executed with i=2, then again with i=3, then again with i=4, then again with i=5, and so on until i=11. When the last number in the iterator has been used, the indented block is skipped altogether and execution resumes following the indented block.

Although for loops are often written using a range(start,finish) statement, you can use for with any kind of collection (a list, for example). Notice that the for loop does not include a conditional test of any kind (as you might expect from C or C++): it just loops through collections of objects or iterators.

While We are Thinking About It

A second kind of popular looping code in Python is the while loop. This type of loop is very similar to loops available in C, C++ or Java. Let's look at an example.

Suppose you have money in your bank account. If you like to eat out for lunch you might be willing to spend all your money to do it. Your thinking might go like this:

As long as I still have money,
    Go out to eat.
    Deduct the restaurant tab from my supply of money

By following these instructions you will just keep going out to eat until all your money is gone. You could write a similar program in python like this:

dinnercost = 15     # cost of dining out
bankaccount = 150   # dollars
while bankaccount > 0:
    print("Yumm.. I would love to eat out tonight!")
    bankaccount = bankaccount - dinnercost
    print("Uh oh.. I only have ${0} left!".format(bankaccount))

Try this code on your own and play with it until you are sure you understand what is going on.


Questions

  1. What do you expect the following program to print?

    for i in range(5):
        print(i)
  2. What do you expect the following program to print?

    for i in [10, 11, 12, 13]:
        print(i)
  3. What do you expect the following program to print?

    for i in ['a', 'b', 'c', 'd']:
        print(i)
  4. What do you expect the following program to print?

    for i in [1, 2, 3]:
        for j in [4, 5]:
            print(i, j)
  5. What do you expect the following program to print?

    b = -4
    while b <= 0:
        b += 1
        print(b)
  6. What do you expect the following program to print?

    for i in [1, 2, 3]:
        for j in range(i):
            print(i, j)
  7. What do you expect the following program to print?

    while 1 == 99:
       print("hi")

⚠️ **GitHub.com Fallback** ⚠️