Home  >  Article  >  Backend Development  >  Why Does My Python Caesar Cipher Function Only Display the Last Shifted Character?

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

Susan Sarandon
Susan SarandonOriginal
2024-10-31 21:30:29789browse

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

Caesar Cipher Function in Python: Troubleshooting Character Shifting Issue

In attempting to craft a Caesar Cipher function in Python, users encounter a recurring issue where only the last shifted character is displayed, rather than an entire ciphered string. To address this, we delve into the code and pinpoint the root cause.

The provided code adheres to the Caesar Cipher principles: it accepts plaintext and shift values, and it iterates through each character, applying the necessary shifts. However, there's a crucial step missing: creating a new string to store the ciphered characters.

Within the function, the initialization of cipherText should occur outside the loop. As it stands, cipherText is reinitialized within each iteration, effectively overwriting the previous ciphered character and resulting in the display of only the last shifted character.

To remedy this issue, we modify 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

    print("Your ciphertext is: ", cipherText)
    return cipherText</code>

Here's how it works:

  • We declare cipherText outside the loop, initializing it as an empty string.
  • Inside the loop, after calculating finalLetter, we append it to the cipherText string.

This updated code correctly accumulates all the shifted characters, producing the desired ciphered string.

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

Statement:
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