我正在尝试使用偶数和奇数定义来加密我的消息。
函数def swap_letters(message)
就是我正在使用的函数:
"for counter in range(0, int(len(message)/2)): ...
; "letter_1.append(even_letters[counter])...
我通过加入new_message
创建letter_1
然后将其返回
我犯了什么错误,如何修复此代码以使其正常运行?
import tkinter as Tk
from tkinter import messagebox, simpledialog, Tk
def is_even(number):
return number % 2 == 0
def get_even_letters(message):
even_letters = []
for counter in range(0, len(message)):
if is_even(counter):
even_letters.append(message[counter])
def get_odd_letters(message):
odd_letters = []
for counter in range(0, len(message)):
if not is_even(counter):
odd_letters.append(message[counter])
return odd_letters
def swap_letters(message):
letter_1 = []
if not is_even(len(message)):
message = message + 'x'
even_letters = get_even_letters(message)
odd_letters = get_odd_letters(message)
for counter in range(0, int(len(message)/2)):
letter_1.append(odd_letters[counter])
letter_1.append(even_letters[counter])
new_message = ''.join(letter_1)
return new_message
def get_message():
message = simpledialog.askstring('Message', 'Enter the secret here: ')
return message
def get_task():
task = simpledialog.askstring('Task', 'Do you want to encrypt or decrypt?')
return task
root = Tk()
while True:
task = get_task()
if task == 'encrypt':
message = get_message()
encrypted = swap_letters(message)
messagebox.showinfo('Ciphertext of the secret message is:', encrypted)
elif task == 'decrypt':
message = get_message()
decrypted = swap_letters(message)
messagebox.showinfo('Plaintext of the secret message is:', decrypted)
else:
break
root.mainloop()
这是我得到的错误:
Traceback (most recent call last):
File "T:\Sublime Text 3\shhhhh.py", line 47, in <module>
encrypted = swap_letters(message)
File "T:\Sublime Text 3\shhhhh.py", line 29, in swap_letters
letter_1.append(even_letters[counter])
TypeError: 'NoneType' object is not subscriptable
[Finished in 21.2s with exit code 1]
[shell_cmd: python -u "T:\Sublime Text 3\shhhhh.py"]
[dir: T:\Sublime Text 3]
[path: C:\Program Files (x86)\Python36-32\Scripts\;C:\Program Files `(x86)\Python36-32\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\dotnet\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files (x86)\Xoreax\IncrediBuild;C:\Users\mwliv\AppData\Local\Microsoft\WindowsApps;]`
答案 0 :(得分:1)
您的get_even_letters
函数未明确返回任何内容,因此它会隐式返回None
,从而导致您稍后看到的错误。添加return
语句应解决问题:
def get_even_letters(message):
even_letters = []
for counter in range(0, len(message)):
if is_even(counter):
even_letters.append(message[counter])
return even_letters # Here!
答案 1 :(得分:0)
只需修改您的代码,如下所示: -
for counter in range(0, int(len(message)/2)):
# You need to verify whether values are None type or not before calling append
if(odd_letters != None):
letter_1.append(odd_letters[counter])
if(even_letters != None):
letter_1.append(even_letters[counter])