繁体   English   中英

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

[英]Taking the return value of a function and changing it into an int 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())

我的问题是,据我所知,确保位置是数字的唯一方法是对其中的函数进行尝试和期望。 但是,当我尝试将函数的返回值转换为int时,代码将引发错误。

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

提前致谢。

对字符串使用isdigit()函数,如果该字符串为数字,则返回True;如果该字符串为字符或为空,则返回false。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM