[英]How to properly use (assert) in this case with Python?
I am a very new user to Python. 我是Python的新手。 I am writing a simple code to return two things: the union of two sets (where each of them contains numbers and words) as well as the length of the union set.
我正在编写一个简单的代码以返回两件事:两个集合的并集(其中每个集合都包含数字和单词)以及联合集的长度。 I am trying to use
assert
with a very simple example as shown below, however, it keeps giving me AssertionError
. 我正在尝试通过一个非常简单的示例使用
assert
,如下所示,但是,它一直在给我AssertionError
。 This is how I defined the function: 这就是我定义函数的方式:
def union(A, B):
AuB = A.union(B)
total = (AuB,len(AuB))
print(total)
then I use this to execute it: 然后我用它来执行它:
A = {1,4,-3, "bob"}
B = {2,1,-3,"jill"}
union(A,B)
assert union(A,B) == ({-3, 1, 2, 4, 'bob', 'jill'}, 6)
However, this is the resulting error: 但是,这是导致的错误:
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:
Please advise what is the best way to use assert
in this case, as I have to use it. 请告知在这种情况下使用
assert
的最佳方法是什么,因为我必须使用它。
Thanks 谢谢
In def union
instead of print
use return. 在
def union
而不是print
使用return。
def union(A, B):
AuB = A.union(B)
total = (AuB,len(AuB))
return total
The problem is not in how to use assert
but what you are trying to assert. 问题不在于如何使用
assert
而在于您要断言的内容。 Your union
function prints a "result" but actually returns None
(because you don't have any return
statement). 您的
union
函数将打印“结果”,但实际上返回None
(因为您没有任何return
语句)。 So you are actually asserting None == ({-3, 1, 2, 4, 'bob', 'jill'}, 6)
which is False
, use return total
instead of (or in addition to if you really want to) print(total)
. 因此,您实际上是在断言
None == ({-3, 1, 2, 4, 'bob', 'jill'}, 6)
这是False
,请使用return total
代替(或在您确实想要的情况下) print(total)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.