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

标签 python function return-value

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 并期望其中包含一个函数。但是当我尝试将函数的返回值转换为 int 时,代码会抛出错误。

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

提前致谢。

最佳答案

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

关于python - python 获取函数的返回值并将其更改为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31644521/

相关文章:

python - 如何减少 matplotlib 等高线图中的小数位数

Python并行编程模型

python - Django 名称错误 : name 'model' is not defined

PHP - 函数内的函数。是好是坏?

c++ - 从共享指针转换为共享指针到 const

python - 来自 Python 的 Win32 长路径

c++ - 使函数接受其参数列表的任何排列的规范方法是什么?

javascript - 如何让函数返回一个 promise

c++ 返回不同的结果

c++ getter不返回值(NULL)