获取函数的返回值并将其更改为int python

2024-04-25 06:52:47 发布

您现在位置:Python中文网/ 问答频道 /正文

shopping_list = []

  def show_help():
    print("\nSeperate each item with a comma.")
    print("Type DONE to quit, SHOW to see the current list, and Help to get this message again.")

  def show_list():
    count=1
    for item in shopping_list:
      print("{}: {}".format(count, item))
      count += 1

  print("Give me a list of things you want to add to the list.")
  show_help()

  while True:
    new_stuff = input("> ")

    if new_stuff == "DONE":
      print ("\n Here's your list:")
      show_list()
      break
    elif new_stuff == "HELP":
      show_help()
      continue
    elif new_stuff == "SHOW":
      show_list()
      continue
    else:
      new_list = new_stuff.split(",")
      def spot_in():
        index = input("Add this item at a certain spot? Press enter to place it at end of list, "
                      "or give me a mumber. Currently {} items in the   list.".format(
         len(shopping_list)))
        return index

      if spot_in():
        try:
          spot = int(spot_in()) - 1
        except ValueError:
          print ("That's not a number, trying to cheat eh? Enter a real number")
          put_in()
        for item in new_list:
          shopping_list.insert(spot, item.strip())
          spot += 1
      else:
        for item in new_list:
          shopping_list.append(item.strip())

我的问题是,据我所知,确保位置是数字的唯一方法是使用try-and-expect函数。但是当我试图将函数的返回值转换为int时,代码抛出了一个错误

有没有更好的方法确保返回的数字是int?或者是否有其他方法将函数的返回值转换为int

提前谢谢


Tags: thetoinnewdefshowcounthelp