python 中的 "def:" 中未定义名称

name not defined in "def:" in python

这个脚本总是给出“name 'stop_condition' is not defined”错误。是什么原因造成的,我该如何解决?

def decode_response(test_input):
 ...
    target_seq[0, 0, target_features_dict['<START>']] = 1.
    
    #A variable to store our response word by word
    decoded_sentence = ''
    
    stop_condition = False

while not stop_condition:
      #Predicting output tokens with probabilities and states
      output_tokens, hidden_state, cell_state = decoder_model.predict([target_seq] + states_value)
#Choosing the one with highest probability
      sampled_token_index = np.argmax(output_tokens[0, -1, :])
      sampled_token = reverse_target_features_dict[sampled_token_index]
      decoded_sentence += " " + sampled_token
...
return decoded_sentence

这是因为缩进虽然循环不在函数内部,但在函数外部,所以 stop_condition 是在函数内部局部定义的。 这是你要找的吗。

def decode_response(test_input):
...
    target_seq[0, 0, target_features_dict['<START>']] = 1.

# A variable to store our response word by word
    decoded_sentence = ''

    stop_condition = False


    while not stop_condition:
    # Predicting output tokens with probabilities and states
        output_tokens, hidden_state, cell_state = decoder_model.predict([target_seq] + states_value)
    # Choosing the one with highest probability
        sampled_token_index = np.argmax(output_tokens[0, -1, :])
        sampled_token = reverse_target_features_dict[sampled_token_index]
        decoded_sentence += " " + sampled_token
...
    return decoded_sentence