我收到一条消息"分配前引用的局部变量'缓存'



我正在尝试制作一个莫尔斯加密器,但我不明白为什么我的代码不起作用。我有一个工作的,我用教程做的,但这个和那个主要有相同的内容。

我的代码:

cheat_sheet = { 'A':'.-', 'B':'-...',
'C':'-.-.', 'D':'-..', 'E':'.',
'F':'..-.', 'G':'--.', 'H':'....',
'I':'..', 'J':'.---', 'K':'-.-',
'L':'.-..', 'M':'--', 'N':'-.',
'O':'---', 'P':'.--.', 'Q':'--.-',
'R':'.-.', 'S':'...', 'T':'-',
'U':'..-', 'V':'...-', 'W':'.--',
'X':'-..-', 'Y':'-.--', 'Z':'--..',
'1':'.----', '2':'..---', '3':'...--',
'4':'....-', '5':'.....', '6':'-....',
'7':'--...', '8':'---..', '9':'----.',
'0':'-----', ', ':'--..--', '.':'.-.-.-',
'?':'..--..', '/':'-..-.', '-':'-....-',
'(':'-.--.', ')':'-.--.-'}
cache = 'beans'
def morse_encrypter (placeholder):
for letter in placeholder:
cache += cheat_sheet [letter]
return cache
b = input ('bruh')
def DO_THE_THING():
placeholder = b
the_answer = morse_encrypter(placeholder.upper())
print (the_answer)
DO_THE_THING ()

问题是您的代码通过+=操作引用了cache的当前值,但它没有定义。默认情况下,函数中使用的变量是它们的本地变量,因此可以通过在morse_encrypter()的最开始添加cache = ''来解决这个问题。

然而。事实上,如果您使用下面所示的生成器表达式,那么您根本不需要该变量:

def morse_encrypter(placeholder):
return ''.join(cheat_sheet[letter] for letter in placeholder)

如果您感兴趣的话,文档中还有关于生成器表达式和相关列表理解的其他信息。

使用

"全局高速缓存";在morse_encrypter((中

这应该可以工作-

cheat_sheet = { 'A':'.-', 'B':'-...',
'C':'-.-.', 'D':'-..', 'E':'.',
'F':'..-.', 'G':'--.', 'H':'....',
'I':'..', 'J':'.---', 'K':'-.-',
'L':'.-..', 'M':'--', 'N':'-.',
'O':'---', 'P':'.--.', 'Q':'--.-',
'R':'.-.', 'S':'...', 'T':'-',
'U':'..-', 'V':'...-', 'W':'.--',
'X':'-..-', 'Y':'-.--', 'Z':'--..',
'1':'.----', '2':'..---', '3':'...--',
'4':'....-', '5':'.....', '6':'-....',
'7':'--...', '8':'---..', '9':'----.',
'0':'-----', ', ':'--..--', '.':'.-.-.-',
'?':'..--..', '/':'-..-.', '-':'-....-',
'(':'-.--.', ')':'-.--.-'}
cache = 'beans'
def morse_encrypter (placeholder):
global cache
for letter in placeholder:
cache += cheat_sheet [letter]
return cache
b = input ('bruh')
def DO_THE_THING():
placeholder = b
the_answer = morse_encrypter(placeholder.upper())
print (the_answer)
DO_THE_THING ()

或者,根据您的程序要求,您可以启动"缓存"的本地实例。

在morse_encrypted 方法中放入cache=''

相关内容

最新更新