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
提前谢谢
对字符串使用isdigit()函数,如果字符串是数字,则返回True;如果字符串有字符或为空,则返回false
相关问题 更多 >
编程相关推荐