Exercises for Lesson 8

Back to Lesson 8

Exercise 1: The song of the animal kingdom

The animal kingdom is larger than just a farm. Your niece just got this new toy for Christmas, and her poor parents have to hear it all the time. To torment your sibling further, you can write a program to display the song lyrics.

When switched to the non-farm side, the song might go like this:

Look, there's a parrot!
Look, there's a parrot!
Hey, ho, here we go,
look there's a parrot!
Squa-awk!

You should write a function that takes in an animal and its sound, and prints out the lyrics. The function signature is given for you. Also, the “docstring” helps users of your function learn about what it does. The first line shows up in IDLE when you try to call your function.

def printAnimalSong(animal, animalSound):
    """
    Prints a song about an animal.

    animal: the animal (a string)
    animalSound: the sound it makes (a string)
    """
    # TODO

Now, write a for loop in main that calls your function for each of these pairs:

  • a monkey that says “oo-oo ah-ah”
  • a lion that says “roar”
  • a parrot that says “squa-awk”

Back to Lesson 8

Exercise 2: Writing functions that return values

Part a: Summing values

Write two functions:

  • sumN(n) returns the sum of the first n natural numbers, i.e., 1+2+3+…+n
  • sumNSquares(n) returns the sum of the squares of the first n natural numbers

Here are their signatures:

def sumN(n):
    """
    Returns the sum of the first n natural numbers.

    n: the number of ints to sum (an int)
    returns: the sum of numbers 1-n (an int)
    """
    # TODO

def sumNSquares(n):
    """
    Returns the sum of the squares of the first n natural numbers.

    n: the number of ints' squares to sum (an int)
    returns: the sum of the squares of 1-n (an int)
    """
    # TODO

Now, write a program that asks the user for a value of n, and uses these functions to print out the sum of the first n natural numbers and the sum of their squares.

def main():
    n = # TODO

    # TODO

Question: does the code still run even if you name your variable something else in main?

Looking for more exercises? They moved to Lesson 9.

Back to Lesson 8