Loop repetition does not behave as expected

Asked

Viewed 76 times

-1

I’m having difficulty doing an exercise of the book 'Eric Matthes' intensive python course the exercises is as follows:

7.8 - Snack bar: Create a list called sandwich_orders and fill it with the names of several sandwiches. Then create an empty list named finished_sandwiches. Browse the list of sandwich orders with a bow and show a message for each request, for example, I have prepared your tuna sandwich. As each sandwich is prepared, transfer it to the list of ready-made sandwiches. After all the sandwiches are ready, show a message listing each prepared sandwich.

sandwich_orders = ['frango', 'peru', 'queijo', 'presunto']
finished_sandwiches = []

    while finished_sandwiches:
        sandwiches = sandwich_orders.pop()
        finished_sandwiches.append(sandwiches)
        for sandwich in finished_sandwiches:
            print('Preparei seu sanduiche de ' + sandwich)

When I run the file in vscode it answers me this:

PS C:\Users\Pedro Moraes\Desktop\stuff\Exercicios\python> & "C:/Users/Pedro Moraes/AppData/Local/Programs/Python/Python38-32/python.exe" "c:/Users/Pedro Moraes/Desktop/stuff/Exercicios/python/lanchonete.py"

It does not "printa" anything in the terminal.

What I must do?

  • The program is acting as expected. finished_sandwiches is empty, so the while finished_sandwiches has nothing to do.

1 answer

3


The program is acting as it should. finished_sandwiches is empty (= []), then the while finished_sandwiches has nothing to do.

Now, if you trade the while for while sandwich_orders:, the thing changes. After all, you want to iterate on the orders and not on the ready ones (which do not exist).

sandwich_orders = ['frango', 'peru', 'queijo', 'presunto']
finished_sandwiches = []

while sandwich_orders:
   sandwiches = sandwich_orders.pop()
   finished_sandwiches.append(sandwiches)

And another thing, I took the for within the while, otherwise you will warn every time you make each of the sandwiches (unless that is the intention, of course).

sandwich_orders = ['frango', 'peru', 'queijo', 'presunto']
finished_sandwiches = []

while sandwich_orders:
   sandwiches = sandwich_orders.pop()
   finished_sandwiches.append(sandwiches)    

for sandwich in finished_sandwiches:
   print('Preparei seu sanduiche de ' + sandwich)

See working on IDEONE.

  • It was just a mistake in the IDE but thank you very much

  • 3

    @Pedromoraesmilagres Then there is something else wrong, because a logically wrong code should not be an "error in the IDE".

  • i restarted the pc and ran the code

Browser other questions tagged

You are not signed in. Login or sign up in order to post.