Python Forum
Issues with Nickel Calculation
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Issues with Nickel Calculation
#1
#Change.PY
# A program to calculate the value of change

def main():
    print("Change Counter")
    print()
    print("Enter count of each coin type.")
    quarters = eval(input("Quarters: "))
    dimes = eval(input("Dimes: "))
    nickels = eval(input("Nickels: "))
    pennies = eval(input("Pennies: "))
    Quarters2 = quarters * .25
    print()
    print("Quarters: ", Quarters2)
    Dimes2 = dimes * .10
    print()
    print("Dimes: ", Dimes2)
    Nickels2 = nickels * .05
    print()
    print("Nickels: ", Nickels2)
    Pennies2 = pennies * .01
    print()
    print("Pennies: ", Pennies2)
    total = Quarters2 + Dimes2 + Nickels2 + Pennies2
    print()
    print("The total value of your change is", total)

main()
It creates the prompt for the amount of change input as requested
it calculates the value of each coin
and it processes the total
however, the math is wrong.
it seems the nickels are not being calculated correctly and i can not figure out how
any help would be fantastic.
Reply
#2
don't use eval, use something like this:
def get_number(text):
    num = None
    while(True):
        try:
            num=int(input('{}: '.format(text)))
            break
        except ValueError:
            print('Not a valid entry, try again')
    return num
and call like:
Quarters2 = get_number('Please enter number of Quarters: ') 
Reply
#3
Do no use eval(),if need float convert to float.
nickels = float(input("Nickels: "))
Nickels2 = nickels * .05

# String foramtting
print('Nickels: {}'.format(Nickels2))
Output:
Nickels: 12 Nickels: 0.6000000000000001
This is how floating point numbers works, Basic Answers.
Can use:
print('Nickels: {:.2f}'.format(Nickels2))
Output:
Nickels: 0.60
Looks better,but the inaccuracy is still there,just less decimal places.
So for finical calculation use Decimal package.
from decimal import Decimal

nickels = input("Nickels: ")
Nickels2 = Decimal(nickels) * Decimal('.05')

# String foramtting
print('Nickels: {}'.format(Nickels2))

# Python 3.6 f-string
#print(f'Nickels: {"Nickels:}')
Output:
Nickels: 12 Nickels: 0.60
Reply
#4
brilliant, thanks a million!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020