2 回答
TA贡献1779条经验 获得超6个赞
您再也不会询问用户,因此循环会无限地执行用户给出的第一个选择。
同时删除该continue语句,您不需要它们,因为所有代码都在其中,elif它还允许您在循环结束时询问用户一个新的选择。
将输入转换为int,你将无法进入循环
def shopping_list(my_str):
my_list = my_str.split(",")
i = int(input("Please choose a number between 1 and 9: "))
while i in range(1, 10):
if i == 1:
print("My shopping list:", my_list)
elif i == 2:
print("The number of items in my shopping list:", len(my_list))
elif i == 3:
# ...
elif i == 8:
print(list(set(my_list)))
else:
break
i = int(input("Please choose a number between 1 and 9: "))
最终完整代码
现在更正一下
mode 5: 返回的remove是None,修改就地如此做
elif i == 5:
product = input("Please enter a product name: ")
my_list.remove(product)
print("The item", product, "remove from the list. The new list is", my_list)
mode 6操作员在列表上+=执行一个操作extend,因此它将添加所有字符,append改为执行
elif i == 6:
product = input("Please enter a product name: ")
my_list.append(product)
print("The item", product, " add to the list. The new list is", my_list)
mode 7如果您忘记创建一个作为主要过滤器过滤器的新列表,那将毫无用处。另外我会说你删除小于 3 或包含非 alpha 的项目,在这里你保留它们。最后使用append
elif i == 7:
new_list = []
for product in my_list:
if len(product) >= 3 and product.isalpha():
new_list.append(product)
my_list = list(new_list)
或者只是使用列表理解
elif i == 7:
my_list = [p for p in my_list if len(p) >= 3 and p.isalpha()]
TA贡献1836条经验 获得超4个赞
我会这样做:(由于代码太多,删除了一些 elifs。)
while True:
i = int(input("Please choose a number between 1 and 9: "))
if i == 1:
print("My shopping list:", my_list)
continue
elif i == 8:
print(list(set(my_list)))
continue
elif i == 9:
break
else:
print("Invalid Number! Try again.")
这是你想要的吗?我不太明白你的要求。
添加回答
举报
