NameError:外部变量未定义

时间:2019-01-08 16:57:05

标签: python function

Score()内部调用Possible_Outcomes()的正确方法是什么?

我不断收到以下错误:

A_win = A_score+(K*(1-win_probability_A))
NameError: name 'A_score' is not defined

我花了一些时间浏览建议的答案,但无法成功实施解决方案。更具体地说,我不明白如何在另一个函数内部使用一个函数的多个返回值。谢谢。

def Score():
    A_score= 1500
    B_score= 1600
    win_probability_A= 1/(1+10**((B_score-A_score)/400))
    win_probability_B= 1/(1+10**((A_score-B_score)/400))
    return A_score, B_score, win_probability_A, win_probability_B

y=Score()

def Possible_Outcomes(y):
    K=int(32)
    A_win = A_score+(K*(1-win_probability_A))
    A_loss = A_score+(K*(0-win_probability_A))
    B_loss = B_score+(K*(0-win_probability_B))
    B_win= B_score+(K*(1-win_probability_B))
    return 

Possible_Outcomes(y)

2 个答案:

答案 0 :(得分:3)

您所拥有的是范围问题。您确实定义了A_score,但仅在函数Score()的上下文中。在此范围之外,Python不知道在哪里寻找A_score或您在此处定义的任何其他变量。

我已经按照您的意图重写了您的代码,

def Score():
    A_score = 1500
    B_score = 1600
    win_probability_A = 1/(1+10**((B_score-A_score)/400))
    win_probability_B = 1/(1+10**((A_score-B_score)/400))
    return A_score, B_score, win_probability_A, win_probability_B

y = Score()

def Possible_Outcomes(values):
    A_score, B_score, win_probability_A, win_probability_B = values
    K = int(32)
    A_win = A_score+(K*(1-win_probability_A))
    A_loss = A_score+(K*(0-win_probability_A))
    B_loss = B_score+(K*(0-win_probability_B))
    B_win= B_score+(K*(1-win_probability_B))
    return A_win, A_loss, B_loss, B_win

Possible_Outcomes(y)

答案 1 :(得分:2)

您可以添加一行以获取scope()函数返回的值

A_score, B_score, win_probability_A, win_probability_B=y

此外,您可以在第二个函数内调用该函数以提高可读性

def Possible_Outcomes():
    K=int(32) # not sure what you are trying to do here can be just K=32
    A_score, B_score, win_probability_A, win_probability_B = Score() # fetch all the values returned by the function 
    A_win = A_score+(K*(1-win_probability_A))
    A_loss = A_score+(K*(0-win_probability_A))
    B_loss = B_score+(K*(0-win_probability_B))
    B_win= B_score+(K*(1-win_probability_B))
    #return # you do not need to return in every function

Possible_Outcomes()

其他方法可能包括使用全局变量,除非保留唯一的选择,否则我不建议使用