Python 凯撒密码函数

Python 凯撒密码函数,python,Python,我正在尝试使用python制作凯撒密码,这是我能做到的: alphabet = ['abcdefghijklmnopqrstuvwxyz'] def create(shift): dictionary={} emptylist=[] int(shift) for x in alphabet: emptylist.append(x) code = "" for letters in emptylist:

我正在尝试使用python制作凯撒密码,这是我能做到的:

alphabet = ['abcdefghijklmnopqrstuvwxyz']

def create(shift):
    dictionary={}
    emptylist=[]
    int(shift)
    for x in alphabet:
        emptylist.append(x)
        code = ""
        for letters in emptylist:
            code = code + chr(ord(letters) + shift)
            dictionary[letters]=code
    return dictionary
它可以让我输入移位值,然后打印:

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    create(2)
  File "C:/Users/Pete/Documents/C- Paisley/A-Level/Computing/dictionarytolist.py", line 11, in create
    code = code + chr(ord(letters) + shift)
TypeError: ord() expected a character, but string of length 26 found

最终产品应该是打印移位的字母。

更简单的方法是


def create(shift):
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    return alphabet[shift:] + alphabet[:shift]

您可以尝试将此代码用于密码。关于如何使用它,它应该是不言自明的

>>> UPPER, LOWER = ord('A'), ord('a')
>>> def encode(text, shift):
    data = list(text)
    for i, c in enumerate(data):
        if c.isalpha():
            base = UPPER if c.isupper() else LOWER
            data[i] = chr((ord(c) - base + shift) % 26 + base)
    return ''.join(data)

>>> def decode(text, shift):
    return encode(text, -shift)

>>> encode('This is a test.', 0)
'This is a test.'
>>> encode('This is a test.', 1)
'Uijt jt b uftu.'
>>> encode('This is a test.', 2)
'Vjku ku c vguv.'
>>> encode('This is a test.', 26)
'This is a test.'
>>> encode('This is a test.', 3)
'Wklv lv d whvw.'
>>> decode(_, 3)
'This is a test.'
>>> 

你需要问一个更具体的问题。任何问题都可以从一开始。有人能告诉我哪里出了问题吗?你可以从告诉我们哪里出了问题以及你不明白的地方开始。应该怎么做?它的作用是什么?你解决这个问题到什么程度了?你把范围缩小到什么了?等等。如果字符串不是'abcdefghijklmnopqrstuvwxyz',对于shift=1的'foo',它将返回'oof'。我以为我们只是在创建密码。这就产生了与明文字母相对应的密码字母。回想起来,我不应该回答这样一个不适定的问题