I was trying to answer an exercise in a beginner's guide to python book. I tried using the while loop first and got the right output, but I experimented by using the for loop, and got an unexpected output. Why the difference in results?
sandwich_orders = ['mushrooom sandwich','cheese sandwich','jalapeno sandwich','bacon sandwich','pastrami','pastrami','pastrami']
finished_sandwiches = []
for sandwich in sandwich_orders:
finished_sandwich = sandwich_orders.pop()
if finished_sandwich != 'pastrami':
print("I made your " + finished_sandwich + ".")
finished_sandwiches.append(finished_sandwich)
else:
print("The deli has run out of pastrami.")
print("\nFinished sandwiches: ")
for sandwich in finished_sandwiches:
print("\t" + sandwich)
print("\n")
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
Output (incorrect):
The deli has run out of pastrami.
The deli has run out of pastrami.
The deli has run out of pastrami.
I made your bacon sandwich.
Finished sandwiches:
bacon sandwich
Correct output:
I made your mushroom sandwich.
I made your jalapeno sandwich.
The deli has run out of pastrami.
The deli has run out of pastrami.
I made your cheese sandwich.
The deli has run out of pastrami.
I made your bacon sandwich.
Finished sandwiches:
mushroom sandwich
jalapeno sandwich
cheese sandwich
bacon sandwich