在Python中创建Caeser密码加密并获取错误

在Python中创建Caeser密码加密并获取错误,python,string,encryption,Python,String,Encryption,Q.编写一个名为shift\u string的函数,该函数将字符串和整数n作为参数,并返回一个新字符串,其中字符串的每个字母都被n字母移位。它也应该适用于反向顺序的否定字母 到目前为止,我已经得出了以下结论: usr_input=input('Please enter string: ') n=input('enter shifts: ') encryption= "" def shift_string(usr_input,n): for i in usr_inpu

Q.编写一个名为
shift\u 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行的封闭范围中定义了局部变量‘加密’。(PyE)”

eval()
的参数必须是包含Python表达式的字符串<代码>输入移位不是有效的表达式,无法对其求值。我猜你的意思是
eval(输入('enter shifts:'))

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

第二个错误是因为
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)

请从下一页重复和。你每篇文章有一个问题。你的最后一段完全超出了这里的范围。“我卡住了”不是堆栈溢出问题。这意味着需要的集合对于堆栈溢出来说太广泛了;你从不调用函数。这能回答你的问题吗?
n = int(input('enter shifts: '))
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)