5
\$\begingroup\$

I am learning Python and I wrote a script that counts how many coins you would need for an amount in dollars. I was wondering if I could make any improvements to it.

def change():
    amnt = float(input("Enter an amount in USD: "))
    quarters = divmod(amnt, 0.25)
    print("Quarters: ", quarters[0])
    amnt = round(quarters[1], 2)
    dimes = divmod(amnt, 0.10)
    print("Dimes: ", dimes[0])
    amnt = round(dimes[1], 2)
    nickels = divmod(amnt, 0.
    print("Nickels: ", nickels[0])
    amnt = round(nickels[1], 2)
    penny = divmod(amnt, 0.01)
    print("Pennies", penny[0])
change()
\$\endgroup\$
10
\$\begingroup\$

Separate input from processing. If you want to test your method with a number of different values, you'll have to call change() multiple times, and enter in the value each time. Instead, change the function to accept the amnt, and you can call it many times passing in the amount of cash as an argument:

def change(amnt):
    # ...

Working with tuples from divmod is awkward. Python has deconstructing assignment, which will take a returned tuple an assign the members to separate variables:

def change(amnt):
    quarters, amnt = divmod(amnt, 0.25)
    print("Quarters: ", quarters)

    dimes, amnt = divmod(round(amnt, 2), 0.10)
    print("Dimes: ", dimes)

For the last operation, you don't use the remainder, so the "throw-away" variable _ can be used for it:

    pennies, _ = divmod(round(amnt, 2), 0.01)
    print("Pennies: ", pennies)

If you import this script into another program, you probably don't want the script to immediately run; rather you just want the change(amnt) function to be defined so this other program can call it. This is done by adding a "guard" at the end of the script, which only runs the code if the script is invoked directly:

if __name__ == '__main__':
    amnt = float(input("Enter an amount in USD: "))
    change(amnt)

In addition to separating input from processing, you might want to separate the processing from the output:

def change(amnt):
    quarters, amnt = divmod(amnt, 0.25)
    dimes,    amnt = divmod(amnt, 0.10)
    nickels,  amnt = divmod(amnt, 0.05)
    pennies = round(amnt / 0.01, 0)

    return list(map(int, [quarters, dimes, nickels, pennies]))

if __name__ == '__main__':
    amnt = float(input("Enter an amount in USD: "))
    quarters, dimes, nickels, pennies = change(amnt)
    print("{} quarters, {} dimes, {} nickels, {} pennies".format(
          quarters, dimes, nickels, pennies))

Despite attempts to fix rounding errors with things like round(amnt,2), calling change(0.85) returns [3, 0, 1, 5], showing that there wasn't quite enough change to make 2 nickels, but after removing 1 nickel, approximately 5 pennies remained. This is caused by floating point math.

We can avoid these issues by switching to integer math, based on the number of pennies:

def change(amnt):
    pennies = round(amnt * 100)   # Convert from dollars to pennies

    quarters, pennies = divmod(pennies, 25)
    dimes,    pennies = divmod(pennies, 10)
    nickels,  pennies = divmod(pennies, 5)

    return quarters, dimes, nickels, pennies

if __name__ == '__main__':
    amnt = float(input("Enter an amount in USD: "))
    quarters, dimes, nickels, pennies = change(amnt)
    print("{} quarters, {} dimes, {} nickels, {} pennies".format(
          quarters, dimes, nickels, pennies))

As mentioned in the comments by @Ilmari, round(...) with only a single argument will round the value to the nearest whole number and return an integer value. When integer values are used with divmod, results are also integers, so switching from dollars-and-cents to integer pennies eliminates the ugly rounding issues.

\$\endgroup\$
  • \$\begingroup\$ +1 for everything except your non-PEP8 formatting, even though it does look nice here. \$\endgroup\$ – Graipher Mar 7 at 6:17
  • 1
    \$\begingroup\$ It might be worth noting that the behavior of single-argument round() autoconverting floats to ints is specific to Python 3. In Python 2, you'd need to explicitly write pennies = int(round(amnt * 100)) if you want the results to be ints. (Of course, using an explicit int() here is OK in Python 3 too, just redundant.) \$\endgroup\$ – Ilmari Karonen Mar 7 at 9:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.