凯撒密码解密脚本开发求助:输入密文与偏移量输出明文
Fixing Your Caesar Cipher Decryption Script
Hey there! Let's break down what's off with your current code and get that decryption working right. I can see you've spent a few days debugging, so let's tackle the key issues step by step:
Key Issues in Your Current Code
- You're encrypting instead of decrypting: Your code adds the shift value to each character's ASCII code, but decryption requires reversing that—you need to subtract the shift instead of adding it.
- Shift value isn't converted to an integer: The
input()function returns a string, so usingsdirectly in arithmetic will throw an error. You need to cast it to an integer withint(s). - Incorrect character range handling: Caesar cipher typically only operates on alphabetic characters (A-Z, a-z), not all ASCII up to 128. Your current logic only accounts for values over 128, but doesn't wrap around properly for lowercase/uppercase letters, and modifies non-alphabet characters (like spaces or punctuation) which should stay untouched.
Corrected Decryption Code
# Get user input (updated prompt to match decryption context) encrypted_text = input("Enter encrypted text: ") shift = int(input("Shift: ")) # Convert shift input to integer def caesar_decrypt(cipher_text, shift_amount): plain_text = "" for char in cipher_text: # Handle uppercase letters if char.isupper(): original_char_code = ord(char) - shift_amount # Wrap around if we go below 'A' if original_char_code < ord('A'): original_char_code += 26 plain_text += chr(original_char_code) # Handle lowercase letters elif char.islower(): original_char_code = ord(char) - shift_amount # Wrap around if we go below 'a' if original_char_code < ord('a'): original_char_code += 26 plain_text += chr(original_char_code) # Leave non-alphabet characters (spaces, punctuation) untouched else: plain_text += char return plain_text # Execute and display the result print("Decrypted plain text:", caesar_decrypt(encrypted_text, shift))
What This Fixes
- Decryption direction: We subtract the shift value to reverse the encryption logic.
- Valid shift type: Converting the input shift to an integer prevents type errors during calculations.
- Proper letter wrapping: We handle uppercase and lowercase letters separately, ensuring they wrap around the alphabet instead of arbitrary ASCII bounds.
- Non-alphabet preservation: Spaces, numbers, and punctuation remain unchanged, which is standard for Caesar cipher implementations.
内容的提问来源于stack exchange,提问作者will309
相关产品推荐
相关产品推荐

