场景
使用练习7-8中的列表sandwich_orders,确保三明治pastrami至少在列表中出现三次。在程序开始附近添加代码,打印一条消息,说明deli已经用完pastrami,然后使用while循环从sandwich_orders中删除所有出现的pastrami。确保没有pastrami三明治在finished_sandwiches结束。
代码我编写了:
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}")下面的是执行代码后的错误
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**发布于 2019-12-19 17:23:01
如果你已经打开了最后一个‘意大利面’三明治,它就不在名单上了,lst.pop
请注意,您没有更改current_sandwich anywere,所以它也是一个infinate循环
顺便说一句,while current_sandwich会让你得到异常,因为你会弹出一个空列表
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}")https://stackoverflow.com/questions/59414172
复制相似问题