CS 100

Logo

Scientific Computing

Activity - More turtles and functions 🐢🐢

In Thonny create a file named moreturtles.py. Save it in the folder CS100/ch1.

Part I: Turtles

  1. Copy the following code to your program. Write in comments what each line does.
    # 
    import turtle
       
    # 
    ada = turtle.Turtle()
       
    # 
    ada.goto(100,100)#
    ada.forward(200) # 
    ada.right(90)    # 
    ada.forward(50)  # 
       
    print("Where is ada? ", ada.position())       # 
    print("Where is ada headed? ", ada.heading()) # 
       
    ada.right(90)
    ada.up()         # 
    ada.forward(150) 
    ada.down()       # 
    ada.forward(50)
       
       
    # 
    def skipForward(bob, hopCount):
        bob.up()
        bob.forward(hopCount)
        bob.down()
        bob.forward(hopCount)
       
    # 
    skipForward(ada, 20)
    skipForward(ada, 30)
    skipForward(ada, 50)
    
  2. After all the previous code, skip a line. Define a new function called drawPentagon that takes one parameter named length.

  3. Call/invoke the function drawPentagon(50) to draw it with side length 50 pixels

  4. Call/invoke the drawPentagon function to draw a pentagon of size 100.

  5. Call/invoke the drawPentagon function to draw a pentagon of size 200.

Part II: Other functions

  1. Define a function add(x, y) that adds its two parameter and prints the result.

  2. Call/invoke your function by typing add(10, 30).

  3. Call again your function with the arguments 524 and 320.

  4. Define a function subtract(x, y) that subracts y from x and prints the result.

  5. Call/invoke the subract function with the arguments 10 and 3.

  6. Define a function hello(name) that has a single parameter that is a string and prints out a few welcoming messages. For example, if “Heather” is passed as an argument via the function call hello("Heather"), then the function should print out:
    Hello, Heather
    Welcome to CS 100
    Have an awesome day!
    
  7. How do the functions we just made (add, subract, and hello) differ from the turtle functions position() and heading()? Write your answer in comments. Hint: try to assign the result to a variable and print the variable.

Part III (Optional): Even more functions!

  1. Define a function circleArea(radius) which takes 1 parameter, computes the area of a circle, and prints the result. Call/invoke your function to test it.

  2. Define a function rectangleArea(width, height) which takes 2 parameters, computes the area of a rectangle, and prints the result. Call/invoke your function to test it.

  3. Define a function named squareArea which takes 1 parameter (the side length), computes the area of a square, and prints the result. Call/invoke your function to test it.

How to submit

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