[英]While loop with multiple IF conditions
我编写了一个程序,它从用户那里接收一个代表购物清单的字符串。 程序要求用户输入一个介于 1 和 9 之间的数字。根据收到的数字,执行以下操作之一: 在做出用户选择后,用户返回主菜单,直到他们 select 数字 9 退出。 语法是正确的,但程序没有打印出需要的内容。 如何解决?
def shopping_list(my_str):
my_list = my_str.split(",")
i = input("Please choose a number between 1 and 9: ")
while i in range(1, 10):
if i == 1:
print("My shopping list:", my_list)
continue
elif i == 2:
print("The number of items in my shopping list:", len(my_list))
continue
elif i == 3:
product = input("Please enter a product name: ")
if product in my_list:
print("This product is in the shopping list.")
else:
print("This item is not in the shopping list.")
continue
elif i == 4:
product = input("Please enter a product name: ")
print("The item", product, "shows", my_list.count(product), "in the list")
continue
elif i == 5:
product = input("Please enter a product name: ")
new_list = my_list.remove(product)
print("The item", product, "remove from the list. The new list is", new_list)
continue
elif i == 6:
product = input("Please enter a product name: ")
my_list += product
print("The item", product, " add to the list. The new list is", my_list)
continue
elif i == 7:
new_list = []
for product in my_list:
if len(product) < 3 or not(product.isalpha()):
new_list += product
continue
elif i == 8:
print(list(set(my_list)))
continue
else:
break
shopping_list("Milk,Cottage,Tomatoes")
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
,修改是in-place so do
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()]
我会这样做:(由于代码太多,删掉一些 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.")
这是你想要的吗? 我不太明白你的要求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.