【发布时间】:2021-12-25 19:01:08
【问题描述】:
我正在尝试将项目附加到列表中,当我输入单词“退出”时,循环应该停止,然后打印我在列表中的项目,但循环继续并仍然问我关于循环,我认为不应该发生。
itemName = ''
itemPrice = '0.0'
while itemName != 'quit'.lower().strip():
itemName = input('What item would you like to add?')
items.append(itemName + ' $' + itemPrice)
itemPrice = input(f'What is the price of {itemName}?')
for item in items[:-1]:
print(item)
【问题讨论】:
-
我把它放在有人用空格或小写字母输入“退出”这个词的情况下。
-
您似乎希望循环在有人键入“退出”时立即停止,但这不是它的工作原理。如果没有
break或continue语句,整个循环体都会执行。 -
但是您在文字字符串
'quit'上调用.lower().strip(),这是没有用的,因为它显然已经小写并被剥离了。
标签: python while-loop append