有人能解释try-except语句中的use-NameError吗?

2024-04-24 18:47:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我在try-except语句中使用NameError,如下所示:

from tkinter import *

# Functions
def chordLabelTextGen(CHORDS, current_chord):
    while True:
        try:
            return_value = CHORDS
            current_chord_pos = return_value.index(current_chord)
            return_value.remove(current_chord_pos)
            return return_value
        except NameError:
            return_value = CHORDS
            return return_value

# Main    
ROOT = Tk()
ROOT.geometry("600x400")
ROOT.title("Chord Changes Log")
STANDARD_TUNING_CHORDS = ["A","B","C","D","E","F","G"]

chord_names = chordLabelTextGen(STANDARD_TUNING_CHORDS, current_chord)
current_chord = chord_names[0]
chord_names = chordLabelTextGen(STANDARD_TUNING_CHORDS, current_chord)
print (chord_names)

但当我通过IDLE运行它时,它会返回以下错误消息:

Traceback (most recent call last):
  File "C:/Users/Jack/Desktop/Python Projects/Gutiar chord changes log PROTOTYPE.py", line 26, in <module>
    chord_names = chordLabelTextGen(STANDARD_TUNING_CHORDS, current_chord)
NameError: name 'current_chord' is not defined

我以为expect语句会喜欢else语句,而运行第二个块,但它似乎不是这样工作的。
有人能给我解释一下吗?你知道吗


Tags: posreturnnamesvalueroot语句currentstandard
2条回答

问题是NameError异常是在main中引发的,而不是在函数中。current_chord在调用函数时不存在于您的作用域中,因此程序在进入函数之前失败,当它试图在堆栈上放置参数时。。。你知道吗

如果你这样写:

try:
    chord_names = chordLabelTextGen(STANDARD_TUNING_CHORDS, current_chord)
except NameError:
    print("Damn, there's an error")

。。。您将看到错误消息。此外,用try/except块处理未定义的变量也不是很好。您应该知道变量何时存在,何时不存在。你知道吗

异常名称错误 在找不到本地或全局名称时引发。这只适用于非限定名称。关联的值是一条错误消息,其中包含找不到的名称。你知道吗

相关问题 更多 >