Skip to main content

Section 4.16 Exercises

Checkpoint 4.16.1.

In Robert McCloskey’s book Make Way for Ducklings, the names of the ducklings are Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack. This loop tries to output these names in order.
Of course, that’s not quite right because Ouack and Quack are misspelled. Can you fix it? Hint: sometimes lists of characters are more useful than a string of characters.

Checkpoint 4.16.2.

Get the user to enter some text and print it out in reverse order.

Checkpoint 4.16.3.

Write a program that uses a for loop to print
One of the months of the year is January
One of the months of the year is February
One of the months of the year is March
etc …
Solution.
for amonth in ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'November', 'December']:
    print("One of the months of the year is", amonth)

Checkpoint 4.16.4.

For the list of numbers below:
  1. Write a loop that prints each of the numbers on a new line.
  2. Write a second loop that prints each number and its square on a new line (just using one print() statement). Make sure you use the exponent operator.

Checkpoint 4.16.5.

Write a program that will go through a list of temperatures and print them out to the user.

Checkpoint 4.16.6.

Write a program that will print out a greeting to each student in the list. This list should also keep track of how many students have been greeted and note that each time a new student has been greeted.

Checkpoint 4.16.7.

A drunk pirate makes a random turn and then takes 100 steps forward, makes another random turn, takes another 100 steps, turns another random amount, etc. A social science student records the angle of each turn before the next 100 steps are taken. Her experimental data is 160, -43, 270, -97, -43, 200, -940, 17, -86. (Positive angles are counter-clockwise.) Use a turtle to draw the path taken by our drunk friend. After the pirate is done walking, print the current heading. Assume that the turtle originally has a heading of 0 and accumulate the changes in heading to print out the final. Your solution should work for any sequence of experimental data.
Solution.
import turtle
wn = turtle.Screen()
lovelace = turtle.Turtle()
# move the turtle forward a little so that the whole path fits on the screen
lovelace.penup()
lovelace.forward(60)
# now draw the drunk pirate's path
lovelace.pendown()
current_heading = 0
for angle in [160, -43, 270, -97, -43, 200, -940, 17, -86]:
    # we use .left() so that positive angles are counter-clockwise
    # and negative angles are clockwise
    current_heading = (current_heading + angle) % 360
    lovelace.left(angle)
    lovelace.forward(100)
# the .heading() method gives us the turtle's current heading in degrees
print("The pirate's final heading was", current_heading)
wn.exitonclick()
You have attempted of activities on this page.