首页 > 解决方案 > python中的凯撒密码没有输出

问题描述

def encrypt(sent,n):
    ''' caesar cipher, insert a sent to encrypt it '''
    # if the shift digit is more than the number of chars to shift, will ask for input again
    if n > 128:
        encryption_digit = int(input("Please insert a number of digits less than 129"))
        encrypt(sent,encryption_digit)
    # makes a list of all the chars
    lis1 = [chr(i) for i in range(128)]    
    # this will be the encrypted list (Reordered list )
    lis2 = []
    # this is the output , the encrypted sentence
    secret = ""
    # a counter to map the chars between the two lists
    con = 0
    # reordering the first list, and appending it into the second list
    for i in lis1[-n:]:
        lis2.append(i)        
    for i in lis1[0:128-n]:
        lis2.append(i)
    # comparing the char in the sentence and the char in lis1 to make the secret sentence
    for l in sent:
        for r in lis1:
            # this will set the counter back to 0, so the lis2[con] won't go out of range
            if con > 128:
                con = 0
            
            if r == l:
                secret = secret + lis2[con]
            else:
                con += 1
    return secret
    
password = input("Insert password\n--> ")
# the number of shifts you want to make
encryption_digit = int(input("What's your caesar cipher shift number\n--> "))
encrypt(password, encryption_digit)

所以就像我没有得到任何输出一样;我知道我仍然需要设置更多条件以使其完美并摆脱所有可能的错误,但这段代码不起作用。顺便说一句,我仍然是评论的新手,但如果你也可以给我反馈我的评论。

标签: python-3.xfunctionencryptioncaesar-cipher

解决方案


该函数encrypt()返回一个值而不是打印一个值。因此,调用时必须将函数放入print()其中,以便返回的值输出到标准输出。

print(encrypt(password, encryption_digit))

推荐阅读