【问题标题】:Building a very simple vending machine in Python用 Python 构建一个非常简单的自动售货机
【发布时间】:2022-06-23 13:32:39
【问题描述】:

我正在尝试构建一个只有一个饮料选项的自动售货机,它计算插入的钱并记住插入的内容并要求插入剩余的钱......例如,如果插入的钱仍然没有足够继续询问和更新剩余的,直到达到饮料的价格......

我快到了,但不知何故需要添加一些代码,以便程序记住并在插入新值时不断更新,直到达到饮料价格

任何帮助将不胜感激!!!

【问题讨论】:

  • 这不是构建while 循环的方法。你永远不会改变你的循环变量total

标签: python


【解决方案1】:

我首先将变量放在首位,然后无限循环仅在满足金额Inserted == Coke 时退出,同时确保在插入的金额高于可乐价格Inserted > Coke 的情况下放弃任何更改。

def main():
    #Settings
    Inserted = 0
    Coke = 50

    while True:
        Inserted += int(input("Insert one coin at a time: "))
        if Inserted > Coke:
            print(f"Giving away {Inserted - Coke} as change ...")
            break # Exiting the while loop
        elif Inserted == Coke:
            print("Enjoy your coke")
            break #Exiting the while loop
        else:
            print(f"You have inserted {Inserted}c")
    

if __name__ == "__main__":
    main()

使用break退出循环

【讨论】:

  • 看起来又好又干净...如果可以,请回答 2 个问题,这有什么不同吗?我的意思是,与循环内的一些变量和循环外的其他变量相比,在循环外执行所有变量?还是只是为了更好地组织代码?另外,回调主函数之前的最后一个 if 是做什么的?非常感谢
  • > 第一个问题。 这是为了组织,我认为这非常重要,尤其是在团队项目中,它使您的代码更清晰,并避免混乱。 >第二个问题检查你是在执行代码还是使用import语法导入它。
  • @AndreCastro 检查此以获取更多信息docs.python.org/3/library/__main__.html
  • 非常感谢...只有一个细节...有没有办法可以添加到 if else 语句中以接受无效条目?例如说一个字符串?而不是抛出错误?
  • 是的,这就是所谓的错误处理,在这种情况下你会try: [Code Block]然后你会except [error type]: [Code to execute when error to found]
【解决方案2】:

有几个错误:

  1. 您只接受一次输入,您需要在循环的每次迭代中接受它
  2. 我认为只有在insert > coke 时才应执行所欠更改
  3. 您需要更正第二个条件,因为如果insert == coke,则不应欠任何更改

要使用的代码:

def main():
    total = 0
    while True:
        total += int(input("Insert one coin at a time: ").strip())
        coke = 50
        print(total)
        if total > coke:
            print("Change Owed =", total - coke)
            return
        elif total == coke:
            print("No Change Owed, Here's a coke ")
            return
        else:
            print("Amount Due =", coke-total)


main()

【讨论】:

  • 太棒了!非常感谢......让我感到困惑的一件事是在循环内部或外部声明某些变量的位置......关于从零开始的总起点,我完全错过了...... :)
【解决方案3】:

每次你用 while insert < coke:return检查插入,基本上结束程序。 Python 不会在不同的脚本执行之间存储变量。您应该做的是使用while True 循环并检查是否插入了总值。

def main():
total_insert = 0 # this variable will keep track of the total insert
coke = 50
while True: # use while True to create a loop that keeps on running.
    insert = int(input("Insert one coin at a time: ").strip())
    total_insert += insert
    if total_insert < coke:
        print("Amount due: ", coke-total_insert)
    if total_insert == coke:
        print("Here is a nice coke!")
        break
    if total_insert > coke:
        print("Here is a nice coke and money:", total_insert-coke) # get the extra money
        break
main()

如果达到某个条件,您可以使用break 语句退出永无止境的while True 循环。

【讨论】:

    【解决方案4】:

    考虑一下:

    coke_price = 50
    payment = coke_price
    
    
    def main():
        global coke_price
        global payment
    
        while True:
            money_input = int(input("Enter one coin at a time: ").strip())
            payment = payment - money_input
    
            if payment < 0:
                print("Change Owed =", -payment)
                return
            elif payment == 0:
                print("No Change Owed, Here's a coke ", payment)
                return
            else:
                print("Amount Due =", payment)
    
    main()
    

    我尚未完善代码,但算法中存在您想要的功能。希望这会有所帮助:D

    附:我更改了一些变量名

    【讨论】:

    • 全局变量不是不好的做法吗?如果代码变得更复杂,这些变量将始终存在于全局范围内?
    • 真的,global 不是推荐的说明函数变量的方式。但是,如果您将它用作常量并且您的代码需要调用几个不同的函数(当您的代码变大时),它会非常方便
    【解决方案5】:

    #自动售货机 def CountMoneyAndIssueDrink():

    total_coins = 0
    coke_price = 10
    change = 0
    
    while True:
        insertedcoins = int(input("Insert coins:"))
        total_coins += insertedcoins
        print(total_coins ," total coins inserted")
        
        if total_coins <= 0:
            print("Insert some coins")
            CountMoneyAndIssueDrink()
            return
        elif(total_coins > coke_price):
            change = total_coins - coke_price
            print("enjoy coke!!, here is the change:", change)
            break
        elif(total_coins == coke_price):
            print("enjoy coke!!")
            break
    

    如果 name == "ma​​in": CountMoneyAndIssueDrink()

    【讨论】:

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