【问题标题】:Creating a Caeser Cipher encryption in Python and Getting Errors [closed]在 Python 中创建 Caesar Cipher 加密并出现错误 [关闭]
【发布时间】:2021-06-09 19:57:50
【问题描述】:

问。编写一个名为shift_string 的函数,它接受一个字符串和一个整数n 作为参数,并返回一个新字符串,其中字符串的每个字母都由n 字母移动。它也应该适用于以相反顺序排列的否定字母。

到目前为止,我想出了这个:

usr_input=input('Please enter string: ')
n=input('enter shifts: ')
encryption= ""

def shift_string(usr_input,n):
    for i in usr_input:
        if i.isupper():
            i_unicode=ord(i) #find position
            
            i_index=i_unicode-ord('A')
            
            new_index= (i_index + n)
            
            new_unicode= new_index +ord('A') #to perform shift
            
            new_character=chr(new_unicode)
            encryption= encryption+new_character #to append string
        else:
            encryption=encryption+i #for non-uppercase
print('Encrypted text is',encryption)

At encryption= encryption+new_character我收到错误消息:

“在赋值前引用的第 23 行封闭范围内定义的局部变量‘加密’...(pyflakes E)”

【问题讨论】:

标签: python string encryption


【解决方案1】:
n=input(eval('enter shifts: '))

eval() 的参数必须是包含 Python 表达式的字符串。 enter shifts 不是一个有效的表达式,你不能计算它。我怀疑你的意思是eval(input('enter shifts: '))

但您不应该使用eval() 来处理用户输入。如果要将输入转换为数字,请使用int()float()

n = int(input('enter shifts: '))

第二个错误是因为encryption 是函数中的一个局部变量,而您试图在初始化之前添加它。您需要在函数内移动encryption = ""。然后就可以返回值了。

def shift_string(usr_input,n):
    encryption = ""
    for i in usr_input:
        if i.isupper():
            i_unicode=ord(i) #find position
            
            i_index=i_unicode-ord('A')
            
            new_index= (i_index + n)
            
            new_unicode= new_index +ord('A') #to perform shift
            
            new_character=chr(new_unicode)
            encryption= encryption+new_character #to append string
        else:
            encryption=encryption+i #for non-uppercase
    return encryption

encrypted = shift_string(usr_input, n)
print('Encrypted text is',encrypted)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    相关资源
    最近更新 更多