A
A
Alexey Yakovlev2021-08-23 21:00:21
Python
Alexey Yakovlev, 2021-08-23 21:00:21

Why does an error occur when accessing an array element?

I am new to python, wanted to write a simple cipher and got an error:

IndexError: list index out of range

Code:

def cipher(text):
    alphabet = list('abcdefghijklmnopqrstuvwxyz')
    list_text = list(text)
    result_text = ''

    for el in list_text:
      change_index = alphabet.index(el) + 3

      if change_index <= len(alphabet):
        result_text += alphabet[change_index]
      else:
        change_index = (alphabet.index(el) + 3) - len(alphabet)
        result_text += alphabet[change_index]

      return result_text

print(cipher('xyz'))

I understand that he cannot find this element in the array, but I wrote a condition by which I bypass this, but for some reason it did not work, what's wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-08-23
@0xD34F

I am new to python

This is not an excuse. Judging by the previous questions, you have at least a year and a half experience using js. They could have learned at least something, for such and such a period.
if change_index <= len(alphabet):
  result_text += alphabet[change_index]

What number do array indexes start with? And, accordingly, what number (relative to length) do they end with?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question