Scientific Computing
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(1, 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
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.
A function is already defined which draws a spiral. Call/invoke the function by typing drawSpiral(bob,90)
after the constructor to create bob and the code to set bob’s speed.
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: you can add a print statement in drawSpiral
to print each time the for loop is executed to help you find out.
Write a function drawTriangle
that takes three parameters - two side lengths and the angle between them - and draws the triangle. Call/invoke the function to test it. Hint: you’ll need to remember the starting location. You can call goto(x,y)
on a turtle to move the turtle from one location to another.
Create a new function named drawOctagon
which must use a for
loop to draw an octagon. Test your function works by calling/invoking it. Hint: You can use the drawTriangle
method from pg. 37 of your book as a model.
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)
Add code to draw a triangle by calling the drawPolygon
function.
Add code to draw a hexagon by calling the drawPolygon
function.
drawCircle
function.Add code that fills your hexagon with the color red (see table at pg. 25).
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.
Revisit the optional code at the end of Activity 3 which uses for loops.
Make sure you saved your work and that it runs without errors. Submit your demoloops.py
file to Moodle.