Old Macdonald Program Using For Loopin Python

1. In your own words, describe the two motivations for defining functions in your programs.

2. We have been thinking about computer programs as sequences of instructions where the computer methodically executes one instruction and then moves on to the next one. Do programs that contain functions fit this model? Explain your answer.

3. Parameters are an important concept in defining functions.

(a) What is the purpose of parameters?

(b) What is the difference between a formal parameter and an actual parameter?

(c) In what ways are parameters similar to and different from ordinary variables?

4. Functions can be thought of as miniature (sub)programs inside of other programs. Like any other program, we can think of functions as having input and output to communicate with the main program.

(a) How does a program provide "input" to one of its functions?

(b) How does a function provide "output" to the program?

5. Consider this very simple function:

(a) What does this function do?

(b) Show how a program could use this function to print the value of y3, assuming y is a variable.

(c) Here is a fragment of a program that uses this function:

answer = 4 result = cube(3) print answer, result

The output from this fragment is 4 27. Explain why the output is not 27 2 7, even though cube seems to change the value of answer to 2 7.

6. Write a program to print the lyrics of the song "Old MacDonald." Your program should print the lyrics for five different animals, similar to the example verse below.

Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! And on that farm he had a cow, Ee-igh, Ee-igh, Oh! With a moo, moo here and a moo, moo there. Here a moo, there a moo, everywhere a moo, moo. Old MacDonald had a farm, Ee-igh, Ee-igh, Oh!

7. Write a program to print the lyrics for ten verses of "The Ants Go Marching." A couple sample verses are given below. You may choose your own activity for the little one in each verse, but be sure to choose something that makes the rhyme work (or almost work).

The ants go marching one by one, hurrah! hurrah! The ants go marching one by one, hurrah! hurrah! The ants go marching one by one. The little one stops to suck his thumb And they all go marching down... In the gound...

To get out

Of the rain. Boom! Boom! Boom!

The ants go marching two by two, hurrah! hurrah!

The ants go marching two by two, hurrah! hurrah!

The ants go marching two by two.

The little one stops to tie his shoe

And they all go marching down...

Of the rain.

Boom! Boom! Boom!

8. Redo any of your favorite programming problems from previous chapters and use a function or two to encapsulate the calculations. For example, a program to compute the volume and surface area of a sphere could use functions sphereVol and sphereArea to do the calculations.

9. Redo some more problems.

0 0

Post a comment