Why is my Python Caesar Cipher only displaying the last shifted character?

Mary-Kate Olsen
Release: 2024-10-30 09:37:27
Original
609 people have browsed it

Why is my Python Caesar Cipher only displaying the last shifted character?

Caesar Cipher Implementation in Python: Encrypted Text not Displaying Correctly

This Python code aims to implement the Caesar cipher, which shifts characters based on user input. However, the resulting cipher text only displays the last shifted character instead of the entire encrypted string. The code provided is as follows:

<code class="python">plainText = raw_input("What is your plaintext? ")
shift = int(raw_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

Analysis

The issue lies within the loop that processes each character in the plaintext. Instead of appending all the shifted characters to the cipherText variable, the code only updates it with the last shifted character. To correct this, the original cipherText variable should be declared before the character processing loop.

Pythonic Implementation

An optimized Caesar cipher implementation can be achieved using Python's string manipulation methods:

<code class="python">def caesar(plaintext, shift):
    alphabet = string.ascii_lowercase
    shifted_alphabet = alphabet[shift:] + alphabet[:shift]
    table = string.maketrans(alphabet, shifted_alphabet)
    return plaintext.translate(table)</code>
Copy after login

By utilizing string.maketrans() and str.translate(), the entire plaintext string can be encrypted with a single operation, resulting in improved performance and code readability.

The above is the detailed content of Why is my Python Caesar Cipher only displaying 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!