Delete the last number I typed

Asked

Viewed 26 times

0

Friends, one more question ( ). Observe the following Code:

Numero = int(input('Digite um Numero'))

inteiro = []
inteiro.append(Numero)

while Numero>0:
  Numero = int(input('Digite um Numero'))
  inteiro.append(Numero)
if Numero<0:
  print(sorted(inteiro,reverse=True))

On my final list, I want you to print the values before the last number.

1 answer

0


The problem actually has to do with how you structured the program. Within the while is reading the number and adds it to the list regardless of its value:

while Numero>0:
  Numero = int(input('Digite um Numero'))
  inteiro.append(Numero) # aqui adiciona mesmo se for 0 ou negativo

The number is added even when it is not valid, because the comparison of the while is done later. To solve just restructure a little:

inteiro = []

while True:
  Numero = int(input('Digite um Numero'))
  if Numero <= 0: # logo após ler o numero vê se é inválido
      break # caso seja termina o while sem adicionar
  inteiro.append(Numero) # se for valido adiciona à lista e segue para o próximo

print(sorted(inteiro,reverse=True))

See code working on Ideone

  • Perfect!!! Thank you very much^^

Browser other questions tagged

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