检查"加密"和#34;解密"在python中使用字符串的Caesar Cipher

时间:2016-09-14 14:42:27

标签: python encryption caesar-cipher

我应该在我的python函数中创建字符串,以表明我的代码的加密和解密工作正常。以下是我的代码。

def encrypt1():
    plain1 = input('Enter plain text message: ')
    cipher = ''

    for each in plain1:
        c = (ord(each)+3) % 126

        if c < 32: 
            c+=31

    cipher += chr(c)

    print ("Your encrypted message is:" + cipher)

encrypt1()

1。)我得到了&#34;不一致地使用标签和空格&#34;错误

2。)如果我的代码有效,我应该如何输入set,constant字符串以获取所需的输入检查(例如,输入meet并获得正确的输入等)

1 个答案:

答案 0 :(得分:1)

您的代码大部分都很好,但我指出了一些问题:

  1. 你的缩进是关闭的。第cipher += chr(c)行应缩进以匹配for循环中的内容
  2. 函数encypt1()不应该带参数;你在方法本身设置plain1,所以你可以在那里声明
  3. 如果你只想处理小写字母,你应该做%123('z'的值),if子句应该检查是否c < 97。如果你想包装可打印的ascii你正在做什么就好了。
  4. 这给出了:

        def encrypt1():
            plain1 = input('Enter plain text message: ')
            cipher = ''
            for each in plain1:
                c = (ord(each)+3) % 126
                if c < 32: 
                    c+=31
                cipher += chr(c)
            print ("Your encrypted message is:" + cipher)
    

    因为您希望能够在多个字符串上测试它,所以您需要将plain1作为参数传递给函数。但是,如果参数未传递给函数,您还希望用户能够输入plain1。为此,我建议一个默认参数。请看下面的注释代码:

    def encrypt1(plain1=""):        # if no argument is passed in, plain1 will be ""
        if not plain1:              # check if plain1 == "" and if so, read input from user
            plain1 = input('Enter plain text message: ')
        cipher = ''
        for each in plain1:
            c = (ord(each)+3) % 126
            if c < 32: 
                c+=31
            cipher += chr(c)
        return cipher               # rather than printing the string, return it instead
    

    所以要测试一下,你可以这样做:

    test_strings = ['hello world', 'harambe', 'Name', 'InputString']
    
    for phrase in test_strings:
        print ("Your encrypted message is:" + encrypt1(phrase))
    

    给出了输出:

    Your encrypted message is:khoor#zruog
    Your encrypted message is:kdudpeh
    Your encrypted message is:Qdph
    Your encrypted message is:LqsxwVwulqj