Fill list and finish python loop

Asked

Viewed 313 times

0

I need help on a problem that asks me to fill in by adding data to a list until it is declared 'end'.

E=[]
i=0
E.append(input('Nome do elemento?'))
while (i!=fim):
  E.append(input('Nome do elemento?'))
  if i == fim:
    break

I made this code, but I can’t break it out of the loop.

2 answers

0


In your example there are some errors:

  1. end is not string
  2. you are comparing end with a variable that contains an integer
  3. while(!=end) already indicates if you type 'end' in the input it will break automatically without you having to do an if for it. But here the end is also not a string.
E=[]

i = input('Nome do elemento: ')
while (i != 'fim'):
    i = input('Nome do elemento: ')
    E.append(i)

print(E)
  • 1

    I was able to solve using your solution as a basis (the problem involved more things). Thank you very much!

  • For nothing! Hug!

0

From what I understand you want to add names inside a list until you decide parar. For this, you can use the following algorithm:

cont = 0
elementos = list()
while True:
    cont += 1
    elementos.append(input(f'Nome do {cont}º elemento: '))

    resp = input('Fim [S/N]? ').upper()
    while (len(resp) != 1) or (resp not in 'SN'):
        print('\033[31mValor INVÁLIDO! Digite apenas "S" ou "N"!\033[m')
        resp = input('Fim [S/N]? ').upper()
    if resp == 'N':
        print(f'\033[32mA lista formada foi: {elementos}\033[m')
        break

Note that when we run the following algorithm we receive the following message: Nome do 1º elemento: . At this point we must enter the name and press Enter. Then we received the following message; Fim [S/N]? . If we wish to continue just type S and press enter. Then the algorithm will request the next name and so on.

Now, if we want to close, just type N and press enter. At this time the algorithm will display the list formed by all the elements previously typed and then will terminate its execution.

Browser other questions tagged

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