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吗?
提前致谢。
答案 0 :(得分:2)
对字符串使用isdigit()函数,如果是数字则返回True,如果有字符或为空则返回false。