From what I understand, the number 0 shall not be counted or entered in the list. In this case, the 0 will only function as flag
stop, that is, when the value is entered "0"
, normal program flow will be terminated. From this moment, the program will display all previously typed values in reverse order, except for the value "0".
To resolve this issue can be used the following code:
lista = list()
while True:
n = int(input(f'Digite um número: '))
if n != 0:
lista.append(n)
else:
cont = 0
while len(lista) >= 1:
print(lista[-1])
del(lista[-1])
cont -= 1
break
Note that when a value is entered, the program checks whether it is diferente
of "0". If different from "0", this value shall be inserted in list and the laço de repetição
- that feeds the list - will be restarted. Otherwise, the repeat loop will be closed and the list will be displayed in reverse order without the value "0".
Also note that, who controls the exibição
of the list elements is 2º while. For this, it checks whether the list size is greater than or equal to "1"
. If so, the last item in the list is displayed (lista[-1])
. Then delete that item from the list and decrement the counter. Then this whole process is redone until the initial list has no more elements.
Another way to resolve this issue would be:
lista = list()
while True:
n = int(input(f'Digite um número: '))
if n != 0:
lista.append(n)
else:
for c in sorted(lista, reverse=True):
print(c)
break
Thank you Andrey.
– Reginaldo Barros da Cunha
It is worth noting that both methods create a new list in memory and, if
seq
is very large, can bring harm to the application, while using the functionreversed
creates a Generator, consuming little memory independent of list size.– Woss
Very well placed @Andersoncarloswoss
– Andrey França