【问题标题】:Getting one function to call another function that creates tuple让一个函数调用另一个创建元组的函数
【发布时间】:2020-05-09 15:33:12
【问题描述】:

我试图让我的结果函数调用我的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'未定义。”

【问题讨论】:

标签: python function tuples


【解决方案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 中的局部变量。这就是为什么它无法打印而您收到错误消息的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多