Python凯撒密码纸条

2024-04-26 21:34:11 发布

您现在位置:Python中文网/ 问答频道 /正文

# Paste the text you want to encipher (or decipher)
original = input("Original text: W fowgsr am roiuvhsf wb hvs Oasfwqob")

# Declare (or guess) the offset. Positive or negative ints allowed
offset = int(input("Offset: 12"))

ciphered = ''

for c in original:
    c_ascii = ord(c)

    if c.isupper():
        c = chr((ord(c) + offset - ord('A')) % 26 + ord('A'))
    elif c.islower():
        c = chr((ord(c) + offset - ord('a')) % 26 + ord('a'))

    ciphered += c

# makes a new file, caesar.txt, in the same folder as this python script
with open("caesar.txt", 'w') as f:
    f.write(ciphered)

“”“ 这是我们老师用来帮我们解密Caeser密码的一些代码,但是由于某些原因,我仍然把输入作为输出,有什么想法解释为什么这不起作用吗?老师证实它起作用了。 """ """ 这个示例句子的12个字符的移位是“我在美国养育了我的女儿”(我需要它区分大小写。)-这个代码也将用同样的移位12来减少更多的句子 “”“


Tags: orthe代码textintxtinputas
2条回答

我认为你操作不正确。看起来您试图将输入直接添加到代码中:

original = input("Original text: W fowgsr am roiuvhsf wb hvs Oasfwqob")
....
offset = int(input("Offset: 12"))

看看“输入”的帮助

Help on built-in function input in module builtin:

input(...) input([prompt]) -> value

Equivalent to eval(raw_input(prompt)).

因此input()的参数是提示,所有的文本都不是作为输入,而是显示为提示。。。你知道吗

试着从命令行运行它,然后在提示符处输入输入。这对我来说很有用。你知道吗

我对这个问题有点困惑,所以这个答案可能是错误的,但是如果您想解码消息,只需将+在偏移量之前交换为-(对于每种情况)。你应该这样做:

# Paste the text you want to encipher (or decipher)
original = input("Original text: W fowgsr am roiuvhsf wb hvs Oasfwqob")

# Declare (or guess) the offset. Positive or negative ints allowed
offset = int(input("Offset: 14"))


ciphered = ''

for c in original:
    c_ascii = ord(c)

if c.isupper():
    c = chr((ord(c) - offset - ord('A')) % 26 + ord('A'))
elif c.islower():
    c = chr((ord(c) - offset - ord('a')) % 26 + ord('a'))

ciphered += c

# makes a new file, caesar.txt, in the same folder as this python script
with open("caesar.txt", 'w') as f:
    f.write(ciphered)

当计算机询问用户是编码还是解码时,您只需添加一个选项即可对消息进行解码。请告诉我,如果这是你要找的,我很高兴尝试去检查代码更多次,如果你需要的话。你知道吗

相关问题 更多 >