程式如下,要求選擇一個產品,然后詢問選擇的金額,然后用戶輸入金額,但如果金額與宣告的值(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))
uj5u.com熱心網友回復:
邏輯可能不一樣
- 不斷要錢(
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/354735.html
標籤:Python for循环 if 语句 while 循环
上一篇:Swift 運算子、回圈、流程控制 for-in, while, if-else, switch-case, guard-else
下一篇:While回圈提前中斷
