我在 Python 中创建了商店计算器,但它有一些错误 [关闭]

Posted

技术标签:

【中文标题】我在 Python 中创建了商店计算器,但它有一些错误 [关闭]【英文标题】:I've Created shop calculator in Python but it have some bugs [closed] 【发布时间】:2021-04-26 17:52:21 【问题描述】:

正如你将在我的代码中看到的那样,我在商店里有 3 件商品,想向顾客展示他买了多少 但代码不起作用! 任何人都可以为我解决它吗?我找不到它的确切问题! 非常感谢你

apple = 0.50
orange = 0.75
banana = 0.25
m = "f"
def calculator():
    m = input("Which fruit u want to purchase? \n press < a > for apple \n press < o > for orange \n press < b > for banana \n press e for exit: ")   
    a_p = 0
    o_p = 0
    b_p = 0
    total = a_p + o_p + b_p
    if m == "a":
          a_t = eval(input("How many ? "))
          a_p = apple * a_t
          total = a_p + total
          main()
    if m == "o":
           o_t = eval(input("How many ? "))
           o_p = orange * o_t
           total = total + o_p 
           main()
    if m == "b":
           b_t = eval(input("How many ? "))
           b_p = banana * b_t
           total = total + b_p
           main()
    else:
        total = str(total)
        print("You've purchased " + total + " dollar from our shop \n Have a nice day !!!")

def main():
    
        calculator();

main()

【问题讨论】:

【参考方案1】:

这是因为在您输入金额后没有任何反应。请参阅第一个 if 块。你打电话给main(),但是你没有任何东西可以打印,因为你打印你的总数是在else中。

if m == "a":
  a_t = eval(input("How many ? "))
  a_p = apple * a_t
  total = a_p + total
  main() # nothing happens after this, it cannot enter the `else` block
else:
    total = str(total)
    print("You've purchased " + total + " dollar from our shop \n Have a nice day !!!")

您正在尝试以递归方式执行此操作,虽然这可以工作,但您最好使用while 循环

为清楚起见的示例:

total = 0
product = None
while product != "e":
    m = input("Which fruit u want to purchase? \n press < a > for apple \n press < o > for orange \n press < b > for banana \n press e for exit: ")
    number = eval(input("How many ? "))
    if m == "a":
        p = apple * number 
    elif m == "o":
        p = orange * number 
    total += p
    product = m # when this is "e" it will break the while loop
    
print("You've purchased " + total + " dollar from our shop \n Have a nice day !!!") # will print after the while loop has finished

【讨论】:

非常感谢你,伙计!祝你一切顺利

以上是关于我在 Python 中创建了商店计算器,但它有一些错误 [关闭]的主要内容,如果未能解决你的问题,请参考以下文章

python中我在父frame中创建了子frame,想让文字显示在每个子frame.却一直不成功,求大腿

用于打开商店的模型与用于创建商店的模型不兼容

QMenu如何设置撕掉窗口标题?

我正在尝试使用 python 文件在 kivy 中添加标签。但它每次都抛出错误

如何使用 Transporter 将 ipa 文件加载到应用商店? “构建”为空

通过 iTunes Connect 在应用商店中保留应用名称