Why does my Caesar Cipher in Python only return the last shifted character?

Barbara Streisand
Release: 2024-10-30 04:21:02
Original
217 people have browsed it

Why does my Caesar Cipher in Python only return the last shifted character?

Caesar Cipher Function in Python

In Python, implementing the Caesar Cipher requires shifting letters based on user-specified input. However, a common error is that the final cipher text only reflects the last shifted character rather than the entire string.

The provided code faces this issue. It iterates through the plaintext and calculates the shifted character, but it updates a single cipherText variable within the loop. As a result, only the last shifted character is added to the output.

To resolve this issue, it's necessary to concatenate the shifted characters into a new string during each iteration of the loop. Here's the corrected code:

<code class="python">plainText = input("What is your plaintext? ")
shift = int(input("What is your shift? "))

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

caesar(plainText, shift)</code>
Copy after login

Now, the cipherText variable is modified and appended with each shifted character, ensuring that the final output contains the complete encrypted string.

The above is the detailed content of Why does my Caesar Cipher in Python only return 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!