Save data inside a vector with loop in Python

1

Good afternoon guys. I have been learning a lot C and C ++, and the part also python. It confuses me a lot of syntaxes at times, because I often think of C and get confused in python. In the case of the python loop, I would like to store data within a vector, and print the data, but it is giving some errors. Help me ae: 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
    
asked by anonymous 01.07.2017 / 17:52

2 answers

3
  • Use range , in conjunction with the for loop, for create a string within the range [0,4] and feed your list.
  • Add an item to the end of the list by calling the append method.
  • Use the for loop to iterate through the list.
  • Retrieve the index of the item within the list by calling the index method.

Your code looks 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))

Example online here .

    
01.07.2017 / 18:24
0
  • Use "insert" to insert elements in the list through its index (in python is not valid by assignment).

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
    
29.10.2018 / 18:55