我开始学习Python,我尝试编写一个简单的购物应用程序代码,我想让用户通过输入名称来删除列表中的项目,无论大小写。
这是代码:
cart = []
items1 = input("Search For What You Want : ")
cart = items1.split("and")
items2 = print("so here is your crate : \n" , cart , "\n Do you want to remove item? : ")
agree = input("")
if agree == "Yes" or "yes":
itemRemove = input("Type the name of item you want to remove : ")
cart.remove(itemRemove)
print("Alr Here Is Your Crate : \n" , cart)
谢谢您的时间<3
我尝试在 itemRemove 变量中输入我将在终端中写入的项目,但出现错误。
打印出您的
cart
列表,您会看到每个条目周围都有空格字符,例如["green eggs ", " ham"]
因此,由于尾随空格,itemRemove
的 "green eggs"
不会与列表的 "green eggs "
匹配。
在下面的示例中,我们在创建购物车列表时删除前导/尾随空格:
cart = []
items1 = input("Search For What You Want : ")
cart = items1.split("and")
# Remove leading/trailing whitespace
for counter in range(len(cart)):
cart[counter] = cart[counter].strip()
items2 = print("so here is your crate : \n" , cart , "\n Do you want to remove item? : ")
agree = input("")
if agree == "Yes" or "yes": # <-- this is always true, but that wasn't the question
itemRemove = input("Type the name of item you want to remove : ")
print(f'"{itemRemove}"')
cart.remove(itemRemove)
print("Alr Here Is Your Crate : \n" , cart)
当您将用户输入拆分为
cart
变量时,您将按 and
进行拆分,但用户可能会添加空格。例如,如果我输入
pickles and onions
然后购物车将如下所示:
['pickles ', ' onions']
相反,您想按字符串分割
' and '
运算符
and
、or
等用于比较条件,而不是字符串、数字、对象或其他东西。 “Yes”和“yes”是两个字符串。相反:
if agree == "Yes" or agree == "yes":
测试用户输入时,您可以通过将字符串转换为小写来使其不区分大小写:
if agree.lower() == "yes"
您可以使用相同的逻辑从购物车中删除该商品:
cart.remove(itemRemove.lower())
最终,真正的答案是学习如何调试代码。第一个问题只需在使用
print(cart)
创建列表后打印出来并查看结果即可解决。