CS 111
Fall 2016
Introduction to Computer Science
HW03: Making change
Due: Wednesday, 09/21 at 23:55
This assignment will give you a little more practice writing
simple Python programs—this time from scratch. It also focuses your
attention on how you can do arithmetic in Python using the +
, -
, *
, /
, and %
operators.
The program
Write a program that asks the user for a purchase price and an amount tendered, and then displays the change in dollars, quarters, dimes, nickels, and pennies. The user should enter both numbers in dollars without the dollar sign (e.g., "34.50" or ".45").
Here is how a typical run of your completed program might look, with user input in red and program output in black:
Price? 34.59 Amount tendered? 40 Report ====== Purchase Price: $34.59 Amount Tendered: $40.00 Change: $5.41 5 one-dollar bills 1 quarter 1 dime 1 nickel 1 penny
Your answer should be the natural one—the one that gives away as little small change as possible. You may assume that both the purchase price and the amount tendered are less than $100, and greater than $0.
A little help
Question #1: How do you turn a string like '34.59' into an integer number of pennies so you can subtract the price from the amount tendered? This is a two-step business:
- First, turn '34.59' into a real number. See the
arithmetic.py
lab for some ideas on how that goes. - Second, multiply your real number by 100 and then turn it into an integer.
Question #2: How do you figure out how many quarters there are in
59 cents? The beauty of integer division is that the remainder is thrown
away. So if you have an int
variable containing 59, and you divide by 25,
what do you get?
Question #3: Once you know how many quarters there are in 59 cents, how do you pursue the number of dimes, nickels, and pennies? Well, if you already know there are 2 quarters in 59 cents, how do you determine what's left over? There are two ways to go. You could subtract 2*25 from 59, of course. But you could also just as well ask "what's the remainder when I divide 59 by 25?" Once you have "9 cents" as your answer, you can go back to Question #2 for your dimes, and then again for your nickels. Got the nickels sorted out? Pennies should be easy.
After you're done
Before stepping away from an assignment like this and moving on to other things, take a little time to think about what the assignment was for. Did the assignment increase your mastery of particular programming tools or language constructs? Did it illuminate some important idea? Even a relatively minor assignment (making change is, I admit, not the most stimulating of computational tasks) is likely to have been assigned for a purpose. If you try to put yourself into the professor's mind (a frightening prospect, I know, but be strong!), you can usually get more out of the assignment than if you just get the program working and then forget about it.
Start early, have fun, and keep those questions coming.