我如何解决 python 中的凯撒密码问题?

How do i fix this problem of caesar cipher in python?

wheel = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
wlen = len(wheel) - 1

c = input("Type a word: ").upper()
key = int(input("Key: "))

encrypted = ''


for x in c:
    f = wheel.find(x) + key 
    if x == " ":
        encrypted = encrypted + " "
    if f > wlen:
        f1 = f - wlen - 1
        encrypted = encrypted + wheel[f1] 
    if f < wlen:
        encrypted = encrypted + wheel[f]

print(encrypted)

此代码无效,我找不到原因。我需要帮助。

例如 "I suck at coding" 给出 "M DWYGO DEX DGSHMRK" 在space之后的所有单词中都有这个额外的D。 "M DWYGO DEX DGSHMRK" 谢谢。

您需要使用elif

if x == " ":
    encrypted = encrypted + " "
elif f > wlen:
    f1 = f - wlen - 1
    encrypted = encrypted + wheel[f1]
elif f < wlen:
    encrypted = encrypted + wheel[f]

为什么:

当你有一个space时,findreturns-1,所以加上你得到的密钥3,所以你输入第一个[=14] =] 因为它是一个 space 但在最后一个 if 中也是 3<25 所以你添加 wheel[f] 这是一个 D,你会只在一个条件下进行

问题在于您的条件检查,因为多个条件同时评估为 True,这不是预期的。

for x in c:
    f = wheel.find(x) + key 
    if x == " ":
        encrypted = encrypted + " "
    elif f > wlen:
        f1 = f - wlen - 1
        encrypted = encrypted + wheel[f1] 
    else:
        encrypted = encrypted + wheel[f]