我正试图让我的results函数调用我的retrieve_pub_vote_summary函数,该函数创建一个元组。然后,我希望我的结果函数打印出元组。
@application.route('/results/')
def results:
publication = "nytimes"
retrieve_pub_vote_summary(publication)
print(pub_tuple)
##############################################
def retrieve_pub_vote_summary(publication):
onevotes = 1
twovotes = 2
pub_tuple = (onevotes, twovotes)
print(pub_tuple)
return pub_tuple
pub_tuple在retrieve_pub_vote_summary中可以正常打印。但这似乎没有结果。我收到“ NameError:未定义名称'pub_tuple'。”
答案 0 :(得分:1)
您的代码中有2个错误:
def results(): # added ()
publication = "nytimes"
pub_tuple = retrieve_pub_vote_summary(publication) # assign the result
print(pub_tuple) # now pub_tuple is defined the line above
##############################################
def retrieve_pub_vote_summary(publication):
onevotes = 1
twovotes = 2
pub_tuple = (onevotes, twovotes)
print(pub_tuple)
return pub_tuple
results() # call results
现在它返回
(1, 2)
(1, 2)
retrieve_pub_vote_summary 中的pub_tuple 是retrieve_pub_vote_summary中的局部变量。这就是为什么无法打印它并导致错误的原因。