当条件满足时,循环不能正常工作



我正试图将项目附加到列表中,当我键入单词";退出";循环应该停止,然后打印我列表上的项目,但循环继续,仍然问我循环中的第二个问题,我认为这不应该发生。

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) 

我看到一个问题,您的.lower().strip处于错误的一侧。此外,我建议使用break,这样您的代码在输入退出时就不会要求价格。

items=[]
itemName = ''
itemPrice = '0.0'
while True:
itemName = input('What item would you like to add?')
if itemName.lower().strip() == 'quit':
break
items.append(itemName + ' $' + itemPrice)
itemPrice = input(f'What is the price of {itemName}?')
for item in items[:-1]:
print(item) 

代码只在询问两个问题后才检查您是否写了quit。此外,您应该将.lower().strip()放在input()函数之后。您的代码总是降低字符串'quit'的大小写。您可以在第一个问题后加上一个if语句,以防止代码在为第一个问题键入'quit'后再问第二个问题。

试着研究一下。

items = []  # storage
totalPrice = 0.0
while True:
itemName = input('What item would you like to add? ')
if itemName.lower() == 'quit':
break
itemPrice = input(f'What is the price of {itemName}? ')  # ask the price before saving the item
if itemPrice.lower() == 'quit':
break
totalPrice += float(itemPrice)  # convert str to float
items.append(f'{itemName} $ {itemPrice}')  # Save to storage

print('items:')
for item in items:
print(item)
print()
print(f'total price: $ {totalPrice}')

输出

What item would you like to add? shoes
What is the price of shoes? 600.75
What item would you like to add? bag
What is the price of bag? 120.99
What item would you like to add? quit
items:
shoes $ 600.75
bag $ 120.99
total price: $ 721.74

最新更新