【发布时间】:2016-04-01 23:53:58
【问题描述】:
我最近才开始自学 Python (3.5.1),并编写了一些基本程序。我正在尝试编写一个程序,允许用户最多购买 3 种产品。但是,我无法获得插入总金额的正确值,我猜这是因为它不断重新初始化自己。任何帮助表示赞赏。另外,我的代码是不是太复杂了,如果是,我该如何简化它?
更新代码:
def main():
displayPrices()
purchaseItems()
def displayPrices():
print("Item ID:\tCost: ")
print("1\t\t$1.25")
print("2\t\t$0.75")
print("3\t\t$0.90")
print("4\t\t$0.75")
print("5\t\t$1.50")
print("6\t\t$0.75")
def purchaseItems():
choice=""
numItems=0
totalCost=0
totalReturned=0
item=0
change=0
x=0
money=float(input("Insert the amount of money you would like to input: $"))
totalInserted=money
while x < 3:
item=int(input("\nWhich item would you like to purchase?\nIf you would like to quit, enter '0': "))
if item == 1:
cost = 1.25
elif item == 2:
cost = .75
elif item == 3:
cost = .90
elif item == 4:
cost = .75
elif item == 5:
cost = 1.50
elif item == 6:
cost = .75
elif item == 0:
print("Thank you for using our Vending Machine. Goodbye!")
break
else:
print("Error. Please enter a valid Item ID [1-6]")
if cost <= money:
change = money - cost
numItems+=1
money=change
totalCost=totalCost+cost
totalReturned=change
print("Thank you for purchasing Item " + str(item) + ". Your change is $" + str(round(change,2)) + ".\n")
x+=1
else:
moneyNeeded = cost - money
print("Please enter an additional $" + str(moneyNeeded) + " to purchase your item.")
newMoney=float(input("Insert the amount of money you would like to input: $"))
totalInserted=money=money+newMoney
# End of Loop
print("Numbers of Items Purchased:", numItems)
print("Total cost of all Items Purchased:", totalCost)
print("Total amount of money inserted:", round(totalInserted,2))
print("Total amount of change returned:", round(totalReturned,2))
main()
看看下面的输出:
项目 ID:成本:
1 $1.25
2 $0.75
3 $0.90
4 $0.75
5 $1.50
6 $0.75
输入您要输入的金额:$0
您想购买哪件商品?
如果您想退出,请输入“0”:1
请输入额外的 1.25 美元购买您的商品。
输入您要输入的金额:$1.00
您想购买哪件商品?
如果您想退出,请输入“0”:2
感谢您购买第 2 项。您的零钱是 0.25 美元。
您想购买哪件商品?
如果您想退出,请输入“0”:1
请输入额外的 1.0 美元购买您的商品。
输入您要输入的金额:$1.0
您想购买哪件商品?
如果您想退出,请输入“0”:1
感谢您购买第 1 项。您的零钱是 0.0 美元。
您想购买哪件商品?
如果您想退出,请输入“0”:0
感谢您使用我们的自动售货机。再见!
购买的物品数量:2
所有购买物品的总成本:2.0
插入的总金额:1.25 --- 这是不正确的
返回的总变化量:0.0
【问题讨论】:
-
请注意,
if结构中每个分支之间的唯一区别是项目的成本。您可以将其他所有内容移出,并使程序大小变为当前大小的一半。 -
@TigerhawkT3 甚至没有注意到我正在复制+粘贴,修复了这个问题,但是我仍然不知道如何处理插入的总数
标签: python loops python-3.x while-loop