O'Reilly logo

Beginning Python®: Using Python 2.6 and Python 3.1 by James Payne

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Appendix A. Answers to the Exercises

Chapter 1

  1. In the Python shell, type the string, "Rock a by baby,\n\ton the tree top,\t\when the wind blows\n\t\t\t the cradle will drop." Feel free to experiment with the number of \n and \t escape sequences to see how this affects what gets displayed on your screen. You can even try changing their placement. What do you think you are likely to see?

  2. In the Python shell, use the same string indicated in Exercise 1, but this time, display it using the print() function. Once more, try differing the number of \n and \t escape sequences. How do you think it will differ?

Exercise 1 Solution

'Rock a by baby,\n\ton the tree top,\t\twhen the wind blows\n\t\t\t the
cradle will drop.'

Because this is not being printed, the special characters (those preceded with a backslash) are not translated into a form that will be displayed differently from how you typed them.

Exercise 2 Solution

Rock a by baby,
        on the tree top,                when the wind blows
                         the cradle will drop.

When they are printed, "\n" and "\t" produce a newline and a tab character, respectively. When the print() function is used, it will render them into special characters that don't appear on your keyboard, and your screen will display them.

Chapter 2

Do the following first three exercises in Notepad and save the results in a file called ch2_exercises.py. You can run it from within Python by opening the file and choosing Run Module.

  1. In the Python shell, multiply 5 and 10. Try this with other numbers as well.

  2. Print ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required