Exit "while" by filling lists

Asked

Viewed 62 times

-1

I need to make a code that uses while and lists, which aims the user to register an undetermined number of people while he wants and put 0 to finish and show on the screen the created list.

It is exercise 5.

So I did but can’t make it stop when you type 0:

print('Digite 0 para terminar o cadastro!')

cont = 1
lista = []
n = ()
while n != 0:
  n = (lista.append(input('Funcionário {}: '.format(cont))))
  cont += 1

print(lista)

1 answer

3


You are adding this to a list and trying to save the result of the list and not the value typed into a variable. This does not work. O append() returns None and not the inserted value.

You should take the value and test if it is time to quit (typed 0) and only if it is not you should add in the list.

Since the output test occurs within the loop there is no reason to test this on the while, which simplifies everything.

print('Digite 0 para terminar o cadastro!')
cont = 1
lista = []
while True:
    n = input('Funcionário {}: '.format(cont))
    if n == "0":
        break
    lista.append(n)
    cont += 1
print(lista)

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

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