【问题标题】:Python Caesar Cypher ScriptPython 凯撒密码脚本
【发布时间】:2019-05-02 17:20:03
【问题描述】:
# 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 Cyphers 的一些代码,但由于某种原因,我仍然将输入作为输出,关于为什么这不起作用的任何想法?老师确认它有效。 """ """ 此例句的 12 个字符的移位是“我在美国养育了我的女儿”(我需要它对大小写敏感。) - 此代码还将解密更多具有相同移位 12 的句子 """

【问题讨论】:

  • 请学习如何调试程序。例如,您可能想要检查 offset 的值。你假设它是12。但可能是0。在这种情况下,您的输入将保持不变。
  • 如果您输入W fowgsr am roiuvhsf wb hvs Oasfwqob12,则为works very well。当它不起作用时,你的输入是什么?
  • Thonny 似乎遇到了麻烦,还有其他人知道一个不在网络浏览器中的 phyton '执行器'程序吗? (请原谅缺乏术语我是新人)

标签: python encryption


【解决方案1】:

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

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

查看“输入”的帮助

帮助builtin模块中的内置函数输入:

输入(...) 输入([提示])-> 值

等效于 eval(raw_input(prompt))。

所以 input() 的参数是提示,所有文本都被视为输入,而是显示为提示...

尝试从命令行运行它,然后在提示符处输入您的输入。当我运行它时,这对我有用。

【讨论】:

    【解决方案2】:

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

    # 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)
    

    这对消息进行解码,您可以在计算机询问用户是编码还是解码时添加一个选项。请告诉我这是否是您要查找的内容,如果您需要,我很乐意尝试多次查看代码。

    【讨论】: