Exercise 1.2

Objectives:

  • Learn how to edit, save, and run Python programs.

  • Simple mathematical calculations and looping.

Files Created: bounce.py and sears.py

(a) The Bouncing Ball

A rubber ball is dropped from a height of 100 meters and each time it hits the ground, it bounces back up to 3/5 the height it fell. Write a program "bounce.py" that prints a table showing the height of the first 10 bounces.

Your program should make a table that looks something like this:

1 60.0
2 36.0
3 21.6
4 12.96
5 7.776
6 4.6656
7 2.79936
8 1.679616
9 1.0077696
10 0.60466176

(b) Cutting and Pasting

The following code fragment contains code from the Sears tower problem in the notes.

# sears.py

bill_thickness = 0.11 * 0.001    # Meters (0.11 mm)
sears_height   = 442             # Height (meters)
num_bills      = 1
day            = 1

while num_bills * bill_thickness < sears_height:
    print day, num_bills, num_bills * bill_thickness
    day = days + 1
    num_bills = num_bills * 2

print "Number of days", day
print "Number of bills", num_bills
print "Final height", num_bills * bill_thickness

If using IDLE, open a new editing window by selecting the "File > New Window" menu option. Copy and paste the code that appears above into this editing Window. Save the code as a program sears.py. Run the code by selecting the "Run > Run Module" menu option. Note, when you run the code you will get an error message. See the next section.

If you are using a different editor, see if you can easily cut and past the code to your editor and run the subsequent file.

(c) Basic Debugging

In the sears.py program, there is a minor typo which causes the program to crash with an error message such as this:

Traceback (most recent call last):
  File "sears.py", line 10, in <module>
    day = days + 1
NameError: name 'days' is not defined

If you’re using IDLE, you can move the cursor to the line in the traceback that shows the file and line number and right click on it. An option to take you to that exact location in the program will appear. Follow it, fix the bug, and re-run the program.

Links