python - 如何在没有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}€".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}€".format(change))
解决方案
逻辑可能不一样
- 不断要钱(
while True
允许写input
一次) - 验证所选择的是否在列表中不等于(a
float
不能等于 alist
) - 增加你的总钱
- 如果你有足够的就停下来
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}€")
其他代码,有一些改进
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}€", 'in total')
else:
print("Exiting the program")
exit(0)
推荐阅读
- python - 使用 VGG 16 作为特征提取器的 U-net 类架构 - 连接层的问题
- machine-learning - 我可以在 500 到 2000 范围内进行聚类,同时建立无监督分类的聚类吗
- android - 将 FCM 和 GCM 用于不同的 API
- python-3.x - 要素“类”作为数据框中的列的问题
- python - Keras 中的全局状态度量和序列掩码
- javascript - 如何使用自定义文件名将画布下载为 PNG?
- java - 为什么这会重复第一个表变量?
- c++ - 如何使用 Qt Custom TableModel(源自 QAbstractTableModel)强制刷新更改的单元格?
- python - 如何从同一目录中的模块导入?
- c - C:错误:数组有不完整的元素类型'void'