【问题标题】:(Python) Vending Machine program returning wrong amount of money inserted? [closed](Python)自动售货机程序返回错误的金额? [关闭]
【发布时间】: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


【解决方案1】:

我很惊讶这条线竟然没有错误地运行,但显然它是一个有效的构造:

totalInserted=money=money+newMoney

在该行中,totalInserted 被分配了 money 的值。但是,当前可用的moneytotalInserted 不同。你真正想要的是:

money += newMoney
totalInserted += newMoney

至于如果您的代码过于复杂,一个更简单的建议是将商品/价格关系存储在字典中:

prices = {1:1.25, 2:.75, ...}

然后你就可以这样做了:

cost = prices[item]

您仍然需要首先检查 item0 还是无效输入。您还有一个从未使用过的变量 choice

【讨论】:

  • 如何检查项目是否为 0 或无效(不在 1-6 范围内)?
  • 像以前一样手动操作,但要利用字典结构。如果 item == 0: ... elif item 不在价格中: ...
  • 我对字典不太满意,因为这是我第一次使用字典,但是我决定使用 if item>0 and itemerror有效的消息
  • 以对您最有意义的方式进行操作并没有错,尤其是在您学习的时候。从长远来看,严格的字典方法很好,因为如果你想添加或删除一个项目,你只需要在一个地方更改你的代码,而现在三个(在字典中,在 displayPrices 中,和在你的 if 语句的范围内)。但是,您可以在到达时越过那座桥。
【解决方案2】:

这可能是一种解决方案。

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():
    money = float(input("How much money would you like to insert?"))
    moneyInserted = money
    items_sold = 0
    items = [1.25, .75, .9, .75, 1.5, .75]
    moneySpent = 0
    total_cost = 0
    x = 1
    while x != 0 and money > 0 and items_sold < 3:
        print("You have $" + str(money) + " left.")
        x = int(input("What item would you like to buy?"))
        if x == 0:
            pass
        elif x < 1 or x > 6:
            print("Please return a valid item number.")
        elif money >= items[x-1]:
            print("Thank you for buying item "+str(x)+".")
            money -= items[x-1]
            moneySpent += items[x-1]
            total_cost += items[x-1]
            items_sold += 1

        else:
            pass
    print("Number of items sold: " + str(items_sold))
    print("Money Inserted: " + str(moneyInserted))
    print("Amount of money spent: " + str(total_cost))
    print("Change amount: " + str(money))


main()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-25
    • 1970-01-01
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多