凯撒的密码函数



我正在尝试使用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.'
>>>