为什么这会产生断言错误,即使它正是所教的内容?

  • 本文关键字:错误 断言 python
  • 更新时间 :
  • 英文 :


我正在为Coursera完成一些东西,这是我制作的代码:

def getFactors(x):
"""Returns a list of factors of the given number x.
Basically, finds the numbers between 1 and the given integer that divide the number evenly.
For example:
- If we call getFactors(2), we'll get [1, 2] in return
- If we call getFactors(12), we'll get [1, 2, 3, 4, 6, 12] in return
"""

factors=[]

for i in range(1,x+1):
if x%1==0:
factors.append(i)
print(factors)

然而,

num = 2
factors_test = [1, 2]
factors = getFactors(num)
assert_equal(factors_test, factors, str(factors) + ' are not the factors of ' + str(num))
num = 12
factors_test = [1, 2, 3, 4, 6, 12]
factors = getFactors(num)
assert_equal(factors_test, factors, str(factors) + ' are not the factors of ' + str(num))
num = 13
factors_test = [1, 13]
factors = getFactors(num)
assert_equal(factors_test, factors, str(factors) + ' are not the factors of ' + str(num))
# test existence of docstring
assert_true(len(getFactors.__doc__) > 1, "there is no docstring for getFactors")
print("Success!")

我得到一个断言错误:

断言错误:[1,2]!=无:无不是2 的因素

正如其他人所指出的,getFactors((函数没有返回值。将此行添加到末尾:
return factors

一旦你这样做,你可能会注意到另一个错误。您正在测试数字模数1==0,这不是很正确。你可能是想测试模量i。你必须更换这条线:

if x%1==0:

这行:

if x%i==0:

很难看到,但第一个使用数字1,第二个使用字母i。

最新更新