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>
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!