feat: P-1.31 completed and commented
This commit is contained in:
@@ -5,3 +5,59 @@ coin to give back as change for the difference between the amount given and the
|
|||||||
to the bills and coins can be based on the monetary system of any current or former government. Try to design your
|
to the bills and coins can be based on the monetary system of any current or former government. Try to design your
|
||||||
program so that it returns as few bills and coins as possible.
|
program so that it returns as few bills and coins as possible.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
# global var, dict of all possible US currency denominations converted to cents
|
||||||
|
denominations = {
|
||||||
|
"hundred-dollar bill(s)": 10000,
|
||||||
|
"fifty-dollar bill(s)": 5000,
|
||||||
|
"twenty-dollar bill(s)": 2000,
|
||||||
|
"ten-dollar bill(s)": 1000,
|
||||||
|
"five-dollar bill(s)": 500,
|
||||||
|
"one-dollar bill(s)": 100,
|
||||||
|
"quarter(s)": 25,
|
||||||
|
"dime(s)": 10,
|
||||||
|
"nickel(s)": 5,
|
||||||
|
"penny(ies)": 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def make_change():
|
||||||
|
# input validation block
|
||||||
|
while True:
|
||||||
|
# try that both vars are formatted correctly and converted to cents
|
||||||
|
try:
|
||||||
|
charged = round(float(input("Enter a dollar amount to be charged: ")) * 100)
|
||||||
|
given = round(
|
||||||
|
float(input("Enter a dollar amount for the amount given: ")) * 100
|
||||||
|
)
|
||||||
|
# print error message if not enough given
|
||||||
|
if given < charged:
|
||||||
|
print("Pay up.")
|
||||||
|
# print error message if a negative amount or 0 is entered
|
||||||
|
elif charged <= 0:
|
||||||
|
print("Please enter a positive dollar amount")
|
||||||
|
else:
|
||||||
|
break
|
||||||
|
# handle ValueError if non-numeric input given
|
||||||
|
except ValueError:
|
||||||
|
print("Please only enter dollar amounts")
|
||||||
|
# calculate change and store it in 'total_change' for printing
|
||||||
|
change = given - charged
|
||||||
|
total_change = change
|
||||||
|
# print message if no change is needed
|
||||||
|
if change == 0:
|
||||||
|
print("No change due.")
|
||||||
|
# iterate over the pre-defined dict and split into names and values
|
||||||
|
for name, value in denominations.items():
|
||||||
|
# store how many of each denomination is needed to make change of the remainder
|
||||||
|
count = change // value
|
||||||
|
# set 'change' as the remainder left after change is issued
|
||||||
|
change = change % value
|
||||||
|
# if there was at least 1 of a denomination given, print how many and its name
|
||||||
|
if count > 0:
|
||||||
|
print(f"{count}", name)
|
||||||
|
# print total change recalculation in dollars
|
||||||
|
print(f"Total change is ${total_change / 100:.2f}")
|
||||||
|
|
||||||
|
|
||||||
|
make_change()
|
||||||
|
|||||||
Reference in New Issue
Block a user