首页 > 解决方案 > 为什么我不能在这里调用函数?

问题描述

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

我的代码:

import time
import math
import random
dict_of_lists={}
def addlist():
  while True:
    try:
      listname=str(raw_input("=>Name of the list:\n"))

      dict_of_lists[listname]={}
      break
    except ValueError:
      print "=>Please enter a valid name.\n"

  print "=>You added a new list named %s.\n" % (listname)
def printlists():
  for lists in dict_of_lists:
    return "-"+lists
def addproduct():
  while True:
    try:
      reachlistname=input("=>Name of the list you want to add a product,Available lists are these:\n %s \nPlease enter one:\n" % (printlists()))
      break
    except ValueError:
      print "=>Please enter a valid list name.\n"
  while True:
    try:
      productname=raw_input("=>Name of the product:\n")
      break
    except ValueError:
      print "=>Please enter a valid name.\n"
  while True:
    try:
      productprice=input("=>Price of the product:\n")
      if isinstance(float(productprice),float):
        break
    except ValueError:
          print "=>Please enter a valid number.\n"
  while True:
    try:
      productcount=input("=>Amount of the product:\n")
      if isinstance(int(productcount),int):
        break
    except ValueError:
      print "=>Please enter a valid number.\n"
  dict_of_lists[reachlistname][productname]={"price":productprice,"count":productcount}
  dict_of_lists[reachlistname]={productname:{"price":productprice,"count":productcount}}
allevents="1-Add a list"+" 2-Add a product to a list"  
def eventtochoose():
  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))
      if  not isinstance(int(event),int):
        print "\n=>Please enter a number.\n"
      else:
        if event==1:
          addlist()
          break
        elif event==2:
          addproduct()
          break

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

while True:
  print "%s" % ("\n"*100)
  eventtochoose()

所以,问题是(我建议你运行代码)它说“=>你想做什么?这是你可以做的所有事情:1-添加列表2-将产品添加到列表请输入你想做的事情之前的数字:”当我回答它时,它根本不会调用函数。

如果我把 1 它应该调用 fucntion addlist 但我认为它没有。没有什么可以解释的,我想如果你想帮助鳄鱼的话,只要看看代码就可以找到问题。谢谢

标签: python

解决方案


在比较之前,您没有将输入转换为整数,因此比较总是错误的:

'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')

推荐阅读