Activity: For loops

PART 1

Create a file demoloops.py and save it to your CS100/ch1 directory. For each of the following exercises, write code to this file and save it. This Is the program that you will eventually submit to Moodle.

  1. Write code using a for loop to print out the numbers 0 to 10 (0 1 2 3 4 …)

  2. Write code using a for loop to print out the numbers 0 to 100 by 10s (0 10 20 30 …)

  3. Write code using a for loop to print out the numbers from -10 to 10 by 2s (-10 -8 -6 …)

  4. Write code using a for loop to print out the numbers from 10 to 0 (10 9 8 7 …)

PART 2

  1. Write a program that uses for loops to draw multiple rectangles. Use the code provided below:
# Draws multiple rectangles
import turtle

t=turtle.Turtle()

def placeRectangle(x,y,height,width):
    t.penup()
    t.goto(x,y)
    t.pendown()
    t.setheading(90)
    t.forward(height)
    t.right(90)
    t.forward (width)
    t.right(90)
    t.forward (height)
    t.right(90)
    t.forward(width)
 
t.speed('fastest') # this makes bob run really fast
t.width(4)
for tall in range(10,100,10):
    placeRectangle(0,0,tall, 50)
  1. Run this program and verify that you get a result that looks like this:

Draw Loop Output 1

This program draws 10 rectangles, each taller than the previous one, but it is difficult to see because they overlap each other.

Modify the program to shift each rectangle over a little bit. Use the following code: (replace the for loop with this:

x = -100
for tall in range(10,100,10):
    placeRectangle(x,0,tall,50)
    x = x + 20

Now the output should look like this:

Draw Loop Output 2

  1. Explain why (in comments) this code changes the output as it does.

Notice that the code inside the placeRectangle() function repeats itself.

  1. Rewrite the code in the placeRectangle() function so that it uses a for loop that iterates two times to draw the rectangle.

Demonstrate that your new function draws a rectangle correctly.

PART 3

  1. Write a drawOctagon function that uses a for loop to draw the octagon instead of eight different sets of turn and forward commands.

Demonstrate that your new function draws a octagon correctly. (Note: the angle between sides of an octagon is 45 degrees.)

How to submit

Make sure you saved your work and that it runs without errors. Submit your demoloops.py file to Moodle.

IMPORTANT

Your program should have FOUR code segments for PART 1, THREE code segments for PART 2 (and a written answer in the comments), and ONE code segment for PART 3. Aside from the loops that print out numbers, you must call all the functions to demonstrate that they work correctly in your code.