0

In this example, you can see that I set plain_text as a parameter to the encrypt function and cipher_text as a parameter to the decrypt function. However, when I only use for example plain_text in my encrypt function, it does not work where as if I use both plain_text and cipher_text, it will work. I am pretty confused about this and would like someone to explain to me why this happens. Thanks.

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', '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_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}")


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


if direction == "encode":
    encrypt(plain_text=text, shift_amount=shift)
elif direction == "decode":
    decrypt(cipher_text=text, shift_amount=shift)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • You are getting it wrong ... the second parameter is `shift_amount` - the number to add/subtract in character table index to encrypt/decrypt it - it is required. And btw. these functions are really weak, I wouldn't use them for encryption at all. – Flash Thunder Jan 08 '22 at 11:31
  • Welcome to Stack Overflow! Please take the [tour]. What do you mean by "does not work"? Please [edit] to clarify. It would help a lot to make a [mre] including example input, expected output, and actual output--or if you get an error, the [full error message with traceback](https://meta.stackoverflow.com/q/359146/4518341). For more tips, see [ask]. – wjandrea Jan 08 '22 at 21:03
  • Maybe this is beside the point, but it's possible to get `IndexError: list index out of range` if `shift` is too large. And there's no validation on `direction`, so if you type something besides `encode` or `decode`, there's no result. You might want to read [Asking the user for input until they give a valid response](/q/23294658/4518341). – wjandrea Jan 08 '22 at 21:12

0 Answers0