0

I have created a list with 26 items.

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

I wish to use shift the letter to next selected position: i.e. "hello" to shift by position 5 and return me text as "mjqqt"

For which I have used the "for loop", and it works fine too until I use a letter z as it is the last item in the list.

Is there a way to loop the list once it has reached the alphabet[25] to restart to position alphabet[0], which means when the shift letter is "z" and shift by position 5 I want it to start again from position 0 to return "e"

I have created a function which for loop to shift each letter in the word and return the encrypted cipher_text.

def encrypt(plain_text, shift_amount):
    cipher_text = ""
    for letter in plain_text:
        position = alphabet.index(letter)
        new_position = position + shift_amount
        cipher_text += alphabet[new_position]
    print(f"The encoded text is {cipher_text}")
encrypt(plain_text=text, shift_amount=shift)

error: Traceback (most recent call last): File "\caesar-cipher\caesar-cipher-4 Final.py", line 36, in encrypt(plain_text=text, shift_amount=shift)

IndexError: list index out of range

depperm
  • 10,606
  • 4
  • 43
  • 67
Hershey
  • 3
  • 2
  • so if the letter is z (25) and the shift is 5, thats an IndexError – depperm Feb 07 '23 at 16:51
  • correct. that's why I need to know if we can make it work by moving alphabet[25] + shift by 5 which is alphabet[30] as by moving it to start of the list at position 4 instead of looking for item at position 30 – Hershey Feb 07 '23 at 16:55

1 Answers1

0

Pretty sure you can do that with modulo:

def encrypt(plain_text, shift_amount):
cipher_text = ""
for letter in plain_text:
    position = alphabet.index(letter)
    new_position = (position + shift_amount) % len(alphabet)
    cipher_text += alphabet[new_position]
print(f"The encoded text is {cipher_text}")

This should work as you expect, you just loop the index if it is past the length of your alphabet

Pollastre
  • 72
  • 7