【问题标题】:Python – Have no error but no return data anyway [duplicate]Python - 没有错误但没有返回数据[重复]
【发布时间】:2017-10-18 19:35:50
【问题描述】:

我喜欢我定义的函数并且在运行程序时没有错误。问题是当我尝试调用一个函数时,什么都没有发生。

from math import sqrt

from recommendations import critics

def sim_distance(prefs, p1, p2):

    si = {}
    for item in prefs[p1]:
        if item in prefs[p2]:
            si[item] = 1
    # If they have no ratings in common, return 0
    if len(si) == 0:
        return 0
    # Add up the squares of all the differences
    sum_of_squares = sum([pow(prefs[p1][item] - prefs[p2][item], 2) for item in prefs[p1] if item in prefs[p2]])
    return 1 / (1 + sqrt(sum_of_squares))

reload (recommendations)
sim_distance(critics, 'Jack Matthews', 'Toby')

【问题讨论】:

  • 你怎么知道什么都没发生?你的代码没有prints,所以它可能会做它的事情然后终止......你的预期输出是什么?
  • 另外你正在返回一些东西,但你没有保留你返回的值。

标签: python function error-handling


【解决方案1】:

您的函数正在返回,但您没有对返回的数据执行任何操作。您可以将返回值分配给变量x = sim_distance(...),然后对该变量执行一些操作。比如print(x)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 2018-08-07
    • 2015-09-26
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 2017-06-13
    相关资源
    最近更新 更多