2

Hi I am trying a simple cipher program that will shift letters by the value the user enters, however, when the word has the letter "z", then it will throw an error that index out of range. So, in order to solve this I tried the easy way which is duplicating the list, but I would like to use a better way to do it. I would like to check if the index is out of range then loop again through the list and perform the same task as shown in the code Thanks a lot!

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']

direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))

def encrypt(plain_text, shift_amount):
  cipher_word = ""
  indexed_letter = len(alphabet)
  for letter in plain_text:
    position = alphabet.index(letter)
    new_position = position + shift_amount
    new_letter = alphabet[new_position]
    cipher_word += new_letter
    
    if new_position > len(alphabet):
      for i in alphabet.index(i - 1)
      
#here where I get stuck

  print(f"You new encrypted word is {cipher_word}")

encrypt(plain_text=text, shift_amount=shift)

timmyx
  • 166
  • 9
  • 2
    It is good context to mention that what you are implementing is the Caesar Cipher. – kluvin Dec 08 '20 at 18:47
  • Maybe you pretend to `try: Except IndexError:` – willcrack Dec 08 '20 at 18:48
  • Does this answer your question? [Circular list iterator in Python](https://stackoverflow.com/questions/23416381/circular-list-iterator-in-python) – Tomerikoo Dec 08 '20 at 18:53
  • 1
    Does this answer your question? [Caesar Cipher Function in Python](https://stackoverflow.com/questions/8886947/caesar-cipher-function-in-python) – DarrylG Dec 08 '20 at 18:53

2 Answers2

5

If the sum of position and shift amount is above 26 then it will show you index out of range error because the total alphabet size is 26. To keep position index always in between 26 then mod the new_position by 26.

new_position = (position + shift_amount)%26
mhhabib
  • 2,975
  • 1
  • 15
  • 29
0

I think this code will solve your problem...

def encrypt(plain_text, shift_amount):
  cipher_word = ""
  for letter in plain_text:
      position = ord(letter)-97  
      new_letter=(chr(97+(position+shift_amount) % 26))    
      cipher_word += new_letter  
  print(f"You new encrypted word is {cipher_word}")
encrypt(plain_text=text, shift_amount=shift)
  
SAIKAT
  • 93
  • 1
  • 6