First, you don’t need this index d
. Just read the data and at the end you add everything in lista_total
at once. Since the data are of different types (a name that is a string and several notes that are numbers), one usually uses tuples instead of lists (of course with lists also works, but when using tuples you already indicate - for anyone who moves the code, including yourself - that they may have data of different types there).
Anyway, to read the data, it could be like this:
lista_total = []
while True:
nome = input('Nome: ')
nota1 = int(input('Nota 1: '))
nota2 = int(input('Nota 2: '))
lista_total.append((nome, [nota1, nota2]))
if input('Quer continuar? [S/N] ').lower() != 's':
break
Note the parentheses of the expression (nome, [nota1, nota2])
: this creates a tuple containing the name in the first position and the list with the notes in the second position. At first glance it may seem that these parentheses are redundant, but they are not. If you just lista_total.append(nome, [nota1, nota2])
, would be passing 2 parameters to append
(the name and the list of notes) and this would give error because append
only takes one parameter. By placing these parentheses, I create the tuple, which is what will be inserted in the list.
In the end, lista_total
will have several tuples, and each of these tuples will have the name in the first position and the list of notes in the second.
Note also that input
already returns a string, so no need to do str(input(etc...))
, is redundant and unnecessary. Finally, I used lower()
to turn the "Want to continue" option into lower case, so you just need to compare it with 's'
.
Then to print, just use enumerate
to browse the list along with the indexes. Then, for each tuple in the list, take the first element (which will be the name), and the second (the list with the notes) and print the information. To calculate the average, simply divide the sum of the notes (using sum
) by quantity (using len
, that picks up the list size):
print('-=' * 15)
alinhamento = '{:<5}{:<20}{}'
print(alinhamento.format('nº','Nome', 'Média'))
print('-' * 30)
for i, dados in enumerate(lista_total):
notas = dados[1]
print(alinhamento.format(i, dados[0], sum(notas) / len(notas)))
I also used the formatting options to align the data: <5
right align with 5 positions (filling unused positions with spaces), and <20
right align with 20 positions (adjust the values according to what you need). Example:
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
nº Nome Média
------------------------------
0 Fulano de tal 3.5
1 Ciclano de qual 5.5
If you want, you can already "dismember" the tuple into variables in itself for
:
for i, (nome, notas) in enumerate(lista_total):
print(alinhamento.format(i, nome, sum(notas) / len(notas)))