在这种情况下 Python 如何正确使用(断言)?
How to properly use (assert) in this case with Python?
我是 Python 的新用户。我正在为 return 两件事编写一个简单的代码:两个集合的并集(其中每个集合都包含数字和单词)以及并集的长度。
我正在尝试将 assert
与一个非常简单的示例一起使用,如下所示,但是,它一直给我 AssertionError
。
这就是我定义函数的方式:
def union(A, B):
AuB = A.union(B)
total = (AuB,len(AuB))
print(total)
然后我用这个来执行它:
A = {1,4,-3, "bob"}
B = {2,1,-3,"jill"}
union(A,B)
assert union(A,B) == ({-3, 1, 2, 4, 'bob', 'jill'}, 6)
然而,这是由此产生的错误:
AssertionError Traceback (most recent call last)
<ipython-input-4-cb63795cc161> in <module>()
2 B = {2,1,-3,"jill"}
3 union(A,B)
----> 4 assert union(A,B) == ({-3, 1, 2, 4, 'bob', 'jill'}, 6)
AssertionError:
请告知在这种情况下使用 assert
的最佳方法是什么,因为我必须使用它。
谢谢
在 def union
而不是 print
中使用 return.
def union(A, B):
AuB = A.union(B)
total = (AuB,len(AuB))
return total
问题不在于如何使用assert
,而在于您要断言的内容。您的 union
函数打印 "result" 但实际上 returns None
(因为您没有任何 return
语句)。所以你实际上断言 None == ({-3, 1, 2, 4, 'bob', 'jill'}, 6)
是 False
,使用 return total
而不是(或者如果你真的想要的话) print(total)
.
我是 Python 的新用户。我正在为 return 两件事编写一个简单的代码:两个集合的并集(其中每个集合都包含数字和单词)以及并集的长度。
我正在尝试将 assert
与一个非常简单的示例一起使用,如下所示,但是,它一直给我 AssertionError
。
这就是我定义函数的方式:
def union(A, B):
AuB = A.union(B)
total = (AuB,len(AuB))
print(total)
然后我用这个来执行它:
A = {1,4,-3, "bob"}
B = {2,1,-3,"jill"}
union(A,B)
assert union(A,B) == ({-3, 1, 2, 4, 'bob', 'jill'}, 6)
然而,这是由此产生的错误:
AssertionError Traceback (most recent call last)
<ipython-input-4-cb63795cc161> in <module>()
2 B = {2,1,-3,"jill"}
3 union(A,B)
----> 4 assert union(A,B) == ({-3, 1, 2, 4, 'bob', 'jill'}, 6)
AssertionError:
请告知在这种情况下使用 assert
的最佳方法是什么,因为我必须使用它。
谢谢
在 def union
而不是 print
中使用 return.
def union(A, B):
AuB = A.union(B)
total = (AuB,len(AuB))
return total
问题不在于如何使用assert
,而在于您要断言的内容。您的 union
函数打印 "result" 但实际上 returns None
(因为您没有任何 return
语句)。所以你实际上断言 None == ({-3, 1, 2, 4, 'bob', 'jill'}, 6)
是 False
,使用 return total
而不是(或者如果你真的想要的话) print(total)
.