Store data inside a Python loop array

Asked

Viewed 11,136 times

1

Good afternoon, you guys. I’ve been learning a lot of C and C++, and the python part too. It confuses me a lot the syntaxes sometimes, because I often think of C and I get confused in python. In the case of python loop, I would like to store data within an array, and print the data, but it is giving some errors. Help me and :c

estudantes = []
i=0
while i < 4:
    estudantes[i] = input("Digite o nome do aluno: ")   
    i+=1

while i<len(estudantes):
    print("Aluno {}: {}".format(i, estudantes[i]))
    i+=1

3 answers

4


  • Utilize range, together with the repeat loop for, to create a sequence within the range [0,4] and feed your list.
  • Add an item at the end of the list by calling the method append.
  • Use the repeat loop for to iterate along the list.
  • Retrieve the item index from within the list by calling the method index.

Your code would look like this:

estudantes = []
for i in range(4):
  estudantes.append(input("Digite o nome do aluno: "))

for x in estudantes:
  print("Aluno {}: {}".format(estudantes.index(x), x))

Online example here.

  • Brigand merchant :D

  • @Alex solved your problem, consider marking the answer as accepted.

0

To store the values within a vector, you can use the while or the for.

Below, I display a way to resolve this issue using the repeat loop for:

# Capturando e tratando a quantidade de estudantes:
while True:
    try:
        n = int(input('Desejas inserir quantos nomes de estudantes? '))
        if n <= 0:
            print('\033[31mValor INVÁLIDO! Digite inteiros maiores que "0"!\033[m')
        else:
            break
    except:
        print('\033[31mValor INVÁLIDO! Digite apenas números inteiros!\033[m')

# Capturando e inserindo o nome de cada estudante na lista "estudantes":
estudantes = list()
for c in range(1, n + 1):
    estudantes.append(input(f'Digite o nome do {c}º estudante: '))

# Exibindo a lista "estudantes":
print(f'\033[32mOs estudantes são: {estudantes}\033[m')

Note the functioning of the algorithm in repl it..

Note that in this code has been implemented a structure for handling errors and exceptions. This block is required to restrict the most common errors at typing time. In this particular case, the number of students is restricted to values only inteiros and maiores that "0".

0

  • Use "Insert" to insert elements in the list via its index (in python it is not valid by assignment).

  • As vc started a new loop "while" it is also necessary to reset the count of the control variable (i=0).

Final result:

estudantes = []
i=0
while i < 4:
     estudantes.insert(i, input("Digite o nome do aluno: "))  
     i+=1
i=0    
while i < len(estudantes):
     print("Aluno {}: {}".format(i, estudantes[i]))
     i+=1

Browser other questions tagged

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