1
The algorithm I am developing should look for an element in any vector. The error happens when the element is not found.
vetor = []
for i in range(1, 5):
vnum = int(input('Digite um valor: '))
vetor.append(vnum)
num = int(input("Digite o valor a ser pesquisado: "))
i = 0
achei = False
while i <= 4 and achei == False:
if num == vetor[i]:
achei = True
else:
i = i + 1
if achei == True:
print(f'O numero {num} esta na posição {vetor[i]}')
else:
print(f'O numero {num} não se encontra na lista.')
And what’s the mistake?
– Woss
When a value is entered that is not in the list it shows this error: if num == vector[i]: Indexerror: list index out of range
– Fabricio Paiva
In doing
i in range(1, 5)
you say i will vary from 1 to 4, because 5 is not inclusive, which results in a list of 4 positions, from 0 to 3. In your loop, you are accessing the positions from 0 to 4, that is, position 4 will never exist in the list.– Woss