Home > Backend Development > Python Tutorial > 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?

Patricia Arquette
Release: 2024-10-29 06:05:02
Original
714 people have browsed it

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:

<code class="python">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</code>
Copy after login

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.

The above is the detailed content of Why Does My Caesar Cipher Function in Python Only Display the Last Shifted Character?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template