Python Function- Return Value is 'not defined'
对于我的加密代码,我尝试从一个函数返回一个值,因为它在下一个函数中使用。我不断地出错,告诉我没有定义"密码文本"。请帮助!
错误:
(第7行)
解密(密文、移位)
名称错误:未定义名称"密码文本"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | 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() |
你的问题是在系 </P >
1 2 | encryption (user_input, shift) decryption (cipher_text, shift) |
作为例外tells你。。。。。。。如果你有包含的追踪与你的问题这将是非常明确的。 </P >
你declare变量的一个函数,函数是局部的。这是一个很好的东西!!!!!!!它见你写的函数类 </P >
1 2 3 4 5 6 7 | def foo(): x = 1 return x * x def bar(): for x in xrange(10): print"Count: %s" % x |
没有他们呼啸着每一其他的弹出菜单。 </P >
如果你呼叫的函数时返回的时候,和你想使用它,你需要使用它的直接,或assign它的东西: </P >
1 2 3 4 5 | # assign x = foo() print x # use directly print"x is %s" % foo() |
在你的案例中,你可以做一个小的变化的assign的结果,
1 2 3 4 | def main(): ... cipher_text = encryption(user_input, shift) decryption(cipher_text, shift) |
它将是等效的(虽然不清)的呼叫,这的任何事情都是别人的 </P >
1 2 | foobar = encryption(user_input, shift) decryption(foobar, shift) |
夏娃的避让或使用一个可变的共 </P >
1 | decryption(encryption(user_input, shift), shift) |
1 2 3 4 5 6 7 8 | 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) |
然后,使用一种呼叫