【问题标题】:I've got some code that isn't doing what I want but I'm not getting an error message我有一些代码没有做我想要的,但我没有收到错误消息
【发布时间】:2019-12-03 17:24:33
【问题描述】:

我正在为我的 GCSE 完成 20 小时的编码任务,我正在尝试编写一些 python 代码来接受食品订单,然后将总数相加并返回所有订单的运行总数,直到那时。我当前的代码存在一些问题,而且我没有收到错误消息,所以我不确定如何修复它以使其达到我想要的效果。

这是我的代码:python code for ordering system

第一个问题是当输入某些项目引用组合时出现问题。总数没有按应有的方式添加,给了我一个小数位数不合理的浮点数,但情况并非总是如此。另一个问题是,当我输入 Y 下另一个订单时,它不让我。虽然当我输入 N 停止订购时,它会做我想做的事。

这是展示这些问题的输出:code that's gone wild with the adding and not allowing me to enter another order

这是一切正常的输出:all good

我已经设法在其他代码位中实现了这两个独立的概念,即停止或继续的 Y/N 和订购代码,但是当我在这里尝试它们时,它不起作用。我们已经研究了很长时间,但仍然无法弄清楚发生了什么。任何帮助将不胜感激!

[edit] 这是我正在努力解决的代码:

>menuItems = [' ', 'Large all day breakfast', 'Small all day breakfast', 'Hot dog', 'Burger', 'Cheese burger', 'Chicken goujons', 'Fries', 'Salad', 'Milkshake', 'Soft drink', 'Still water', 'Sparkling water']
>menuPrices = [0.00, 5.50, 3.50, 3.00, 4.00, 4.25, 3.50, 1.75, 2.20, 2.20, 1.30, 0.90, 0.90]
>orderTotal = 0 #resets the order total so that the total is accurate
>runningTotal = float(0.0)
>orderWords = 'Order: '
>orderItem = 1
>ordering = True
>while ordering == True:
>    while orderItem != 0:
>       orderItem = int(input('Please list the item reference number: '))
>       orderTotal = orderTotal + (menuPrices[orderItem])
>       orderWords = orderWords + ' ' + (menuItems[orderItem])
>       runningTotal = runningTotal + (menuPrices[orderItem])
>   else:
>       print(orderWords)
>       print('Your total is: £', orderTotal)
>       ordering = False
>else:
>   proceed = str(input('Do you want to place another order (Y/N)? '))
>   if proceed == 'Y':
>       ordering = True
>   if proceed == 'N':
>       ordering = False
>       print('Running total: £', runningTotal)
>   else:
>       ordering = True

【问题讨论】:

  • 如果不将代码发布在问题正文中而不是使用图像,您将获得反对票。您可以使用“如何提问”指南来帮助您...stackoverflow.com/help/how-to-ask

标签: python error-handling


【解决方案1】:

正如@quaabaam所说,请将有问题的代码复制并粘贴到问题中,这样我们可以在需要时复制它然后进行调试。

我假设 menuItems 和 menuPrices 应该是关联的,这意味着“全天大早餐”的价格为 5.50。在这种情况下,最好使用字典。例如:

Menu = {"Large all day breakfast" : 5.50, "Small all day breakfast" : 3.50, ... }

这样,您只需调用价格,例如x = Menu["Large all day breakfast"] x 的价格,在本例中为 5.50。

另外,您可能希望将 while ordering == True 更改为函数,例如

def ordering():
    while True:
        orderItem = int(input(...
        if orderItem != 0:
            orderTotal += menuPrices[orderItem] #x += 1 means that you increase x by 1, it's basically what you wrote but different notation
        else:
            print(orderWords)
        ...
            break
    proceed(runningTotal)


def proceed(runningTotal):
    proceed = ...
    elif proceed == "N":
        ordering()

如果你还没有研究过函数,我强烈推荐它,因为它非常重要,尤其是在这里

【讨论】:

  • 非常感谢!因为我无法从学校访问这个网站,也无法从家里访问代码,所以我很难将它粘贴到我的问题正文中,但我会尽快得到它,我一定会看看您建议的解决方案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-14
  • 1970-01-01
  • 1970-01-01
  • 2019-12-15
  • 2021-05-14
  • 2016-08-13
  • 1970-01-01
相关资源
最近更新 更多