为什么我不能在这里调用函数?

时间:2018-05-01 19:42:18

标签: python

大家好,我正在制作一个购物清单 - 创作者代码,但最后我遇到了一个惊喜。

我的代码:

{{1}}

所以,问题是(我建议你运行代码)它说" =>你想做什么?以下是您可以做的所有事情:  1 - 添加列表2 - 将产品添加到列表中 请在您要做的事情之前输入数字:"当我提出答案时,它根本就没有给这个问题打电话。

如果我放1它应该调用fucntion添加列表,但我认为它没有。没有什么可以解释我想只要查看代码并找到问题,如果你想帮助鳄鱼。 THX

2 个答案:

答案 0 :(得分:0)

在比较之前,您没有将输入转换为整数,因此比较始终为false:

'1' == 1 # false

尝试:

event = raw_input("=>What would you like to do? Here are the all things you can do:\n %s\nPlease enter the number before the thing you want to do:" % (allevents))
try:
    event = int(event)
    if event == 1:
        addlist()
    elif event == 2:
        addproduct()
        break
except ValueError:
    print('Please enter a valid input')

答案 1 :(得分:0)

执行int(event)时,如果可能,会返回int,如果不是,则会引发ValueError。因此,测试结果的类型对您没有任何好处 - 如果您的代码到目前为止,类型必须是int

您已经拥有处理ValueError的代码,因此您不需要针对同一问题进行任何其他测试。

同时,您想要从int(event)开始获得的号码。这可能是== 1;原始字符串'1'永远不会是== 1

所以:

while True:
    try:
      event=raw_input("=>What would you like to do? Here are the all things you can do:\n %s\nPlease enter the number before the thing you want to do:" % (allevents))
      event = int(event)
      if event==1:
        addlist()
        break
      elif event==2:
        addproduct()
        break

    except ValueError:
      print "\n=>Please enter a valid input.\n "