返回值应为列表,但不为';我没能按预期回来Python新手

返回值应为列表,但不为';我没能按预期回来Python新手,python,Python,这一定是一个非常简单的解决方案,我在最后一个小时没有想到。我尝试构建这个测试函数,其中test_cases列表的返回值应该与test_case_answers列表中的值匹配,但是由于某种原因,测试用例1和测试用例2失败了。当我打印测试用例的返回值时,它们返回正确的答案,但由于某些原因,测试用例1和测试用例2返回False import math test_cases = [1, 9, -3] test_case_answers = [1, 3, 0] def custom_sqrt(nu

这一定是一个非常简单的解决方案,我在最后一个小时没有想到。我尝试构建这个测试函数,其中test_cases列表的返回值应该与test_case_answers列表中的值匹配,但是由于某种原因,测试用例1和测试用例2失败了。当我打印测试用例的返回值时,它们返回正确的答案,但由于某些原因,测试用例1和测试用例2返回False

import math

test_cases = [1, 9, -3]  
test_case_answers = [1, 3, 0]

def custom_sqrt(num):  
    for i in range(len(test_cases)):  
        if test_cases[i] >= 0:  
            return math.sqrt(test_cases[i])  
        else:  
            return 0

for i in range(len(test_cases)):  
    if custom_sqrt(test_cases[i]) != test_case_answers[i]:  
        print "Test Case #", i, "failed!"


custom_sqrt(test_cases)

你的循环次数太多了。在
custom_sqrt
中,您尝试循环所有测试用例,但是您返回了第一个测试用例的值,因此您永远无法访问其余的测试用例。从
custom_sqrt
中删除您的循环,这样就可以:

def custom_sqrt(num):
    if num >= 0:
        return math.sqrt(num)
    else: 
        return 0

您的
自定义\u sqrt
函数需要一个整数列表,而您给它一个整数。

将测试放在函数中可能不是一个好主意;一旦完成,您就必须删除它,然后该函数就不再是您测试的函数了

import math

def test_fn(fn, data):
    for inp, exp in data:
        outp = fn(inp)
        if outp == exp:
            print("  passed")
        else:
            print("*** FAILED: {}({}) returned {}, should be {}".format(fn.__name__, inp, outp, exp))

def custom_sqrt_a(num):
    try:
        return math.sqrt(num)
    except ValueError:
        return 0.

def custom_sqrt_b(num):
    if num < 0.:
        return 0.
    else:
        return math.sqrt(num)

custom_sqrt_test_data = [
    ( 1., 1.),
    ( 9., 3.),
    (-3., 0.)
]
test_fn(custom_sqrt_a, custom_sqrt_test_data)
test_fn(custom_sqrt_b, custom_sqrt_test_data)
导入数学
def测试_fn(fn,数据):
对于inp,exp in数据:
输出=fn(输入)
如果outp==exp:
打印(“通过”)
其他:
打印(“***失败:{}({})返回{},应为{}”。格式(fn.\uuu name\uuuu,inp,outp,exp))
def自定义_sqrt_a(数量):
尝试:
返回math.sqrt(num)
除值错误外:
返回0。
def自定义_sqrt_b(数量):
如果num<0:
返回0。
其他:
返回math.sqrt(num)
自定义测试数据=[
( 1., 1.),
( 9., 3.),
(-3., 0.)
]
测试fn(自定义测试数据)
测试fn(自定义测试数据,自定义测试数据)

底部的
定制(测试用例)
实际上在那里吗?只是好奇。为什么你希望它会返回一个列表?这里的代码显然只返回一个整数,调用方也将每个返回值与一个整数进行比较。