Scenario :
Using the list sandwich_orders
from Exercise 7-8, make sure the sandwich pastrami
appears in the list at least three times. Add code near the beginning of your program to print a message saying the deli has run out of pastrami
, and then use a while loop to remove all occurrences of pastrami
from sandwich_orders
. Make sure no pastrami
sandwiches end up in finished_sandwiches
.
Code I have written :
sandwich_orders=['egg&mayo','cheese&onion','chicken&sweetcorn','pastrami','pastrami',
'egg&watercress','pastrami','pastrami']
finished_sandwiches=[ ]
current_sandwich=sandwich_orders.pop()
print(f"\nYour Sandwich has been prepared : {current_sandwich}")
while current_sandwich:
print(f"\nCurrent sandwich is {current_sandwich}!!")
if current_sandwich=='pastrami':
sandwich_orders.remove('pastrami')
print(f"\n{current_sandwich} has been removed from the orders")
else:
finished_sandwiches.append(current_sandwich)
print(f"\nYour Sandwich has been prepared : {current_sandwich}")
print(f"\nList of finshed swandwiches : {finished_sandwiches}")
print(f"\nList of Sandwich Orders recieved : {sandwich_orders}")
below is the Error after executing the code :
Traceback (most recent call last):
File "C:\Users\thota01\AppData\Local\Programs\Python\Python38\Python_Input_whileLoops\movietickets.py", line 9, in <module>
sandwich_orders.remove('pastrami')
**ValueError: list.remove(x): x not in list**
If you already pop the last 'pastrami' sandwich, its not longer in the list, lst.pop
Notice that you don't change current_sandwich anywere, so its also a infinate loop
btw, while current_sandwich
will make you to get exception, cause you will be poping an empty list
sandwich_orders=['egg&mayo','cheese&onion','chicken&sweetcorn','pastrami','pastrami',
'egg&watercress','pastrami','pastrami']
finished_sandwiches=[ ]
print(f"\nYour Sandwich has been prepared : {current_sandwich}")
while sandwich_orders:
current_sandwich = sandwich_orders.pop()
print(f"\nCurrent sandwich is {current_sandwich}!!")
if current_sandwich=='pastrami':
print(f"\n{current_sandwich} has been removed from the orders")
else:
finished_sandwiches.append(current_sandwich)
print(f"\nYour Sandwich has been prepared : {current_sandwich}")
print(f"\nList of finshed swandwiches : {finished_sandwiches}")
print(f"\nList of Sandwich Orders recieved : {sandwich_orders}")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.