program that puts people on a list

Asked

Viewed 78 times

1

someone can explain the mistake?

quantidadePessoas = int(input('quantas pessoas estarão na festa?'))

lista = []

for pessoa in range(quantidadePessoas):
    nome = input('inscreva uma pessoa')
    lista[pessoa] = 'olá ' + nome + ', seja bem vindo\n'

print(lista)

1 answer

2


One list (list) in Python does not work as the vectors or "arrays" are used in C and other languages. In particular, it is created empty (or from another sequence) - and you add new elements as you need.

That is: it is not created with a fixed initial size. And that is what causes the problem in your program. The line lista[pessoa] = ... is absolutely correct for alter the content of the list in the position pessoa. The problem is that this position does not yet exist - so your program stops with a IndexError.

The solution is, rather than trying to change the content of lista in position pessoa, simply call the list python to include a new element at the end of the list. This method is the .append(<elemento>).

Your show would look like this:

quantidadePessoas = int(input('quantas pessoas estarão na festa?'))

    lista = []

    for pessoa in range(quantidadePessoas):
        nome = input('inscreva uma pessoa')
        lista.append(f'olá {nome}, seja bem vindo\n')

    print(lista)

(I also switched the use of "+" to concatenate text with an "f string" - which allows the use of variables directly inside the quotes - this is simpler to type and more readable - but note the letter f before quotation marks . This only works from Python 3.6 onwards)

Another way - but not normal in Python, would be to force the creation of a list element for each person you include, before the for - this can be done by creating a list with a single element, and using the multiplication operator * to "add this list to itself" N times - and so have a list with the required length. The beginning of the program would look like this (and then the rest of the code you wrote would work like this):

quantidadePessoas = int(input('quantas pessoas estarão na festa?'))

lista = [''] * quantidadePessoas
...

(Here is an important tip for your future questions: always include the error that Python prints - we call "traceback" - along with your problem code. In this case, the program is short and it is easy to see what happens - but in general the traceback describes exactly where is the error and what happened, which is important in a more complex program)

Browser other questions tagged

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