I am trying to append items to a list, and when I type the word "quit" the loop should stop, and then print the items I have on my list, but the loop continues and still asks me the second question on the loop, which I think should not be happening.
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)
CodePudding user response:
I see one problem, you have your .lower().strip
on the wrong side.
Also, I would suggest using break
so that your code won't ask for a price if quit is inputted.
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)
CodePudding user response:
The code only checks if you wrote quit after it asks both questions. Also, you should put your .lower().strip()
after the input()
function. Your code always lowercases and strips the string 'quit'
. You can put an if
statement after the first question with a break to prevent your code from asking you the second question after you typed 'quit'
for the first question.
CodePudding user response:
Try to study this.
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}')
Output
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