2016 September 14,

CS 111: for Loops

Computers excel at doing repetitive tasks quickly without complaint. This idea is called looping, because it's kind of like running around in a loop. It's a basic ingredient in programming.

Let's start by converting a secret message from upper-case to lower-case. Copy and paste this code into a text file, save the file, and run the program.

upper = 'JDAVISTHEDOLPHINARRIVESATMIDNIGHTYOURFRIENDJBIEBER'
lower = ''
for character in upper:
    lower = lower + chr(ord(character) + 32)
print(lower)

In the preceding code, the variable character takes on many values. On the first pass through the loop, it has value 'J'. On the next pass it has value 'D'. On the next pass, it has value 'A'. And so on. On each pass it is a character (type str) and something is done to that character. Namely, the character is converted from upper-case to lower-case, and then appended to the string lower.

Question 08A: What is the type of ord(character)? Of chr(ord(character) + 32)? Of lower? Of lower + chr(ord(character) + 32)?

Question 08B: What happens if you re-run the program with + 32 changed to - 32? Alternatively, what happens if you put spaces between the words in the original secret message?

Here's another example, based on our earlier graphics work.

import turtle
fred = turtle.getturtle()
fred.fillcolor(1.0, 0.0, 0.0)
fred.begin_fill()
for i in range(3):
    fred.forward(200)
    fred.left(90)
fred.forward(200)
fred.end_fill()

For reasons that we will explain later, range(3) is the sequence 0, 1, 2. So the variable i takes on those three integer values in rapid succession. For each value, something is done to the turtle fred. Intuitively, each pass through the for loop makes one side of a square, and the final fred.forward(200) makes the final side of the square.

Question 08C: Instead of drawing a square with 90-degree corners, let's have the turtle draw a hexagon with 60-degree corners. Show the new code.

Question 08D: Going back to the problem of converting a string from upper-case to lower-case, you should be able to solve it using a for loop that looks like for i in range(len(upper)): How?