我是python的新手,这是我最近收到的代码,它一直工作到第29行。这是发生错误的地方:
Traceback (most recent call last):
File "N:/computing/11woojos_A453/A453_ASSIGNMENT/Task two/task 2 SO.py", line 30, in <module>
print (keyword_encrypt)(shift_key, phrase)
TypeError: 'NoneType' object is not callable
我的代码:
#!/usr/bin/env python2
from itertools import islice, cycle
phrase = input('message you would like to encrypt: ')
shift_key = input('shift key: ')
def keyword_encrypt(key, phrase): # e.g. "ba","abcde"
# make phrase and key into arrays of letters (equal length)
phrase = [ letter for letter in phrase.lower()] # e.g. ['a', 'b', 'c', 'd', 'e']
key = list(islice(cycle(key.lower()), len(phrase))) # e.g. ['b', 'a', 'b', 'a', 'b']
encrypted = []
for i in range(len(phrase)):
k_letter = (ord(key[i]) - ord('a'))
p_letter = (ord(phrase[i]) - ord('a'))
new_letter = p_letter + k_letter
if new_letter >= 26:
new_letter -= 26
new_letter = chr(new_letter + ord('a'))
encrypted.append(new_letter)
# make the list a string again with the join command
return "".join(encrypted)
print ('encrypted message:')
print ('_')
print (keyword_encrypt)(shift_key, phrase)
答案 0 :(得分:1)
代码正在尝试调用print()
函数的结果:
result = print (keyword_encrypt)
result(shift_key, phrase)
这不会奏效,因为print()
总是会返回None
。
您可能打算调用keyword_encrypt()
函数并打印该调用的返回值:
print(keyword_encrypt(shift_key, phrase))
代码写得有点奇怪,括号和空格,但是如果你实际上用Python 2运行它(作为文件的第一行#!
尝试做),那么发布的代码实际上是工作。这是因为print
是Python 2中的一个语句,keyword_encrypt
周围的括号实际上被忽略了。