"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does My Caesar Cipher Function in Python Only Display the Last Shifted Character?

Why Does My Caesar Cipher Function in Python Only Display the Last Shifted Character?

Published on 2024-11-08
Browse:672

Why Does My Caesar Cipher Function in Python Only Display the Last Shifted Character?

Caesar Cipher Function in Python: Encrypted Strings

When implementing a Caesar Cipher function in Python, a common issue arises where the final encrypted text displays only the last shifted character. To resolve this, it's necessary to understand the issue causing this behavior.

In the provided code, the loop iterates over each character in the plaintext. For alphabetic characters, it shifts the character's ASCII code based on the provided shift value. However, each shifted character is appended to an empty string named cipherText within the loop. As a result, only the last character is displayed as the encrypted text.

To rectify this issue, the ciphertext must be constructed within the loop and returned once all characters have been processed. This can be achieved by modifying the code as follows:

def caesar(plainText, shift):
    cipherText = ""
    for ch in plainText:
        if ch.isalpha():
            stayInAlphabet = ord(ch)   shift
            if stayInAlphabet > ord('z'):
                stayInAlphabet -= 26
            finalLetter = chr(stayInAlphabet)
        cipherText  = finalLetter

    return cipherText

With this modification, the cipherText string is initialized once and all shifted characters are appended to it within the loop. When the function returns, the encrypted string contains all shifted characters, as intended.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3