Activity: For loops

Create a file demoloops.py and save it to your CS100/ch1 directory. Add the following code and put your name in comments at the top of the file.

import turtle

# define your functions here
def printManyThings():
    print("TODO 1")

def drawSpiral(myTurtle, maxSide):
    for sideLength in range(5, maxSide+1, 5):
        myTurtle.forward(sideLength)
        myTurtle.right(90)


# call your functions here
printManyThings()

bob = turtle.Turtle()
bob.speed('fastest') # this makes bob run really fast
  1. Implement the function printManyThings so that it prints all multiples of 5 in the range 5-100 (inclusive), that is, 5, 10, 15, …., 100. Test that it works.

  2. A function is already defined which draws a spiral. Call/invoke the function by typing drawSpiral(bob,100) after the constructor to create bob and the code to set bob’s speed.

  3. How many times is the for loop in drawSpiral executed? Write your answer inside the string that prints “answer to question 3 is: (your answer here)”. Hint: think about what values sideLength can have; you can add a print statement in drawSpiral to print each time the for loop is executed to help you find out.

  4. Create a new function named drawOctagon which must use a for loop to draw an octagon (8-sided polygon). Test your function works by calling/invoking it. Hint: You can use the drawTriangle function below as a model.
    def drawTriangle(myturtle, sideLength):
        for side in range(3):
            myturtle.forward(sideLength)
            myturtle.right( 360 / 3 )
    
  5. Add the following functions to the top of your file:
    def drawPolygon(myTurtle, sideLength, numSide):
        turnAngle = 360 / numSide
        for i in range(numSide):
            myTurtle.forward(sideLength)
            myTurtle.right(turnAngle)
    
    def drawCircle(myTurtle, radius):
        circumference = 2*3.14*radius
        sideLen = circumference / 360 # note that 360 is the number of sides
        drawPolygon(myTurtle, sideLen, 360)
    
  6. Add code to draw a triangle by calling the drawPolygon function. Note: you do not need to implement a new function.

  7. Add code to draw a hexagon by calling the drawPolygon function. Note: you do not need to implement a new function.

  8. Add code to draw a circle by calling the drawCircle function. Note: you do not need to implement a new function.

If you have time, try the next steps:

  1. Use the turtle to plot the function y=x2 for all x-coordinates from -25 to 25. Hint: to begin at the start point, use function up to lift up the pen and down to place it down again to start plotting.

  2. Revisit the optional code at the end of Activity 3 which uses for loops.

How to submit

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