You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

凯撒密码解密脚本开发求助:输入密文与偏移量输出明文

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 using s directly in arithmetic will throw an error. You need to cast it to an integer with int(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

  1. Decryption direction: We subtract the shift value to reverse the encryption logic.
  2. Valid shift type: Converting the input shift to an integer prevents type errors during calculations.
  3. Proper letter wrapping: We handle uppercase and lowercase letters separately, ensuring they wrap around the alphabet instead of arbitrary ASCII bounds.
  4. Non-alphabet preservation: Spaces, numbers, and punctuation remain unchanged, which is standard for Caesar cipher implementations.

内容的提问来源于stack exchange,提问作者will309

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:23:51