首页 > 解决方案 > 如何在没有python错误的情况下打印Congrats

问题描述

程序如下,要求选择一个产品,然后询问选择的金额,然后用户输入金额,但如果金额与声明值(mo)不同,程序会打印“错误硬币”,但是当用户输入正确的硬币和数量时,它应该只打印代码的“找零”部分。在我的程序中,它打印“零钱”,然后是错误的硬币值

prod = ["Coffe", "Coffee with milk", "Chocolate", "Chocolate with milk"]
cost = [1.5, 1.8, 2.1, 2.4]
mo = [0.1, 0.2, 0.5, 1, 2, 5, 10]

item_number = len(prod)

print("\nPick an item:")

for number in range(0, item_number, 1):
    print(number + 1,
    prod [number],
    '{0:.2f}€'.format(cost[number]))

print ("0 Exit")

choice = int(input("Please pick an item from (1-4) or hit 0 to exit: ")) -1

if choice < item_number and choice >= 0:
    print("You should input", "{0:.2f}€&quot;.format(cost[choice]), 'in total')
else:
        print("Exiting the program")
        exit(0)

money = float(input("How much do you enter?; "))

while money < cost[choice]:
    money += float(input("You should insert "+str("{:.2f}".format(cost[choice] - money))))

if money != mo:
    print("Invalid amount.\nPlease enter a valid coin: 0.1 / 0.2 / 0.5 / 1 / 2 / 5 / 10")
else:
    print("Try again")
change = money - cost[choice]

print("Change {0:.2f}€&quot;.format(change))

标签: pythonfor-loopif-statementwhile-loop

解决方案


逻辑可能不一样

  • 不断要钱(while True允许写input一次)
  • 验证所选择的是否在列表中不等于(afloat不能等于 a list
  • 增加你的总钱
  • 如果你有足够的就停下来
money = 0
while True:
    new_money = float(input(f"You should insert {cost[choice] - money:.2f}: "))
    if new_money not in mo:
        print("Invalid amount.\nPlease enter a valid coin: " + "/".join(map(str, mo)))
        continue
    money += new_money
    if money >= cost[choice]:
        break
change = money - cost[choice]
print(f"Change {change:.2f}€&quot;)

其他代码,有一些改进

print("\nPick an item:")
for number in range(item_number, ):
    print(f'{number + 1} {prod[number]} {cost[number]:.2f}€')
print("0 Exit")

choice = int(input("Please pick an item from (1-4) or hit 0 to exit: ")) - 1
if 0 < choice <= item_number:
    print(f"You should input {cost[choice]:.2f}€&quot;, 'in total')
else:
    print("Exiting the program")
    exit(0)

推荐阅读