Python 函数- Return 值为 'not defined'

Python Function- Return Value is 'not defined'

对于我的加密代码,我正在尝试 return 来自一个函数的值,因为它会在下一个函数中使用。我一直收到错误消息,告诉我名称 'cipher_text' 未定义。请帮忙!

错误:

(第 7 行)

解密(cipher_text,移位)

NameError: 名称 'cipher_text' 未定义

def main():
    user_input = input ("Enter string: ")
    shift = int(input ("Enter a shift that is between 1 and 26: "))
    while shift<1 or shift>26:
        shift = input ("ERROR: Shift must be between 1 and 26: ")
    encryption (user_input, shift)
    decryption (cipher_text, shift)
    frequency (user_input)

def frequency(user_input): 
    freq_char = None
    for char in user_input: 
        charcount = user_input.count(char) 
        if (charcount != 0): 
            freq_char = char
    print (freq_char)
    return fre_char

def encryption(user_input, shift):
    cipher_text = ''
    for char in user_input: #for every character in input
        if char == ' ':
            cipher = char
            cipher_text += cipher
        else:
            cipher_num = (ord(char))+(shift)%26 #using ordinal to find the number
            cipher= ''
            cipher = chr(cipher_num)# using chr to convert back to a letter
            cipher_text += cipher
    print ("The encrypted text is:",cipher_text)
    return(cipher_text)


def decryption (cipher_text, shift):
    decrypt_text = ''
    cipher_text = ''
    for char in cipher_text: #for every character in the encrpted text
        decrypt_num = (ord(char))+(int(shift))%26
        decrypt= ''
        decrypt = chr(decrypt_num)
        decrypt_text += decrypt
    print("The decrypted text is:", decrypt_text)
    return(decrypt_text)

main()

def main() 应该是 def main(cipher_text) 您还可以为 cipeher_text:

设置默认值
def main(cipher_text=""):
    user_input = input ("Enter string: ")
    shift = int(input ("Enter a shift that is between 1 and 26: "))
    while shift<1 or shift>26:
        shift = input ("ERROR: Shift must be between 1 and 26: ")
    encryption (user_input, shift)
    decryption (cipher_text, shift)
    frequency (user_input)

然后只需调用 main() 使用值示例 main('some value') 或者如果您如前所述定义了默认值则为空。

你的问题在行

    encryption (user_input, shift)
    decryption (cipher_text, shift)

正如异常告诉你的那样。如果您在问题中包含回溯,这将非常清楚。

您在一个函数中声明的变量是该函数的局部变量。这是一件好事!它可以让你编写像

这样的函数
def foo():
    x = 1
    return x * x

def bar():
    for x in xrange(10):
        print "Count: %s" % x

没有他们互相炸毁。

如果你调用了一个函数 returns 并且你想使用它,你需要直接使用它,或者将它分配给一些东西:

# assign
x = foo()
print x
# use directly
print "x is %s" % foo()

在您的情况下,您可以进行最小的更改,将 encryption 的结果分配给新变量 cipher_text

def main():
      ...
    cipher_text = encryption(user_input, shift)
    decryption(cipher_text, shift)

将其称为其他名称是等效的(尽管不太清楚)

    foobar = encryption(user_input, shift)
    decryption(foobar, shift)

甚至完全避免使用变量

    decryption(encryption(user_input, shift), shift)