为什么调用函数有效但断言函数会导致断言错误?
Why does calling the function work but asserting the function results in an assertion error?
我写了一个工作正常的函数,但是当我为它写一个断言代码时,它给出了一个断言错误。这段代码的唯一问题是修复断言错误。
def frequency(x, y):
'''Get the frequency (the number of occurrences) of an element in a sequence.
: param sequence: the sequence in which the element must be counted
: param element: the element whose frequency we want to obtain
: return: the frequency of the element in the sequence'''
a = list(x)
print(a.count(y))
def test_frequency():
# Tests
assert frequency('texts', 'e') == 1
assert frequency('texts', 'a') == 0
assert frequency('texts', 's') == 1
assert frequency('texts', 't') == 2
# limit tests
assert frequency('ttt', 't') == 3
assert frequency('', 'x') == 0
print('test_frequency: ok')
test_frequency()
frequency(x = input("Enter a word: "), y = input("Enter a letter(symbol): "))
这个小问题是函数打印它的值,而不是 returning 它们。
Python 有一些相当可疑的行为 returning None
每当函数结束时没有 return 语句导致此类不幸的错误。
解决方案是在 return a.count(y)
而不是 print(a.count(y))
结束。
这是因为您的函数正在打印值而不是返回计数。
def frequency(x, y):
a = list(x)
return a.count(y)
def test_frequency():
# Tests
assert frequency('texts', 'e') == 1
assert frequency('texts', 'a') == 0
assert frequency('texts', 's') == 1
assert frequency('texts', 't') == 2
# limit tests
assert frequency('ttt', 't') == 3
assert frequency('', 'x') == 0
print('test_frequency: ok')
test_frequency()
frequency(x = input("Enter a word: "), y = input("Enter a letter(symbol): "))
我写了一个工作正常的函数,但是当我为它写一个断言代码时,它给出了一个断言错误。这段代码的唯一问题是修复断言错误。
def frequency(x, y):
'''Get the frequency (the number of occurrences) of an element in a sequence.
: param sequence: the sequence in which the element must be counted
: param element: the element whose frequency we want to obtain
: return: the frequency of the element in the sequence'''
a = list(x)
print(a.count(y))
def test_frequency():
# Tests
assert frequency('texts', 'e') == 1
assert frequency('texts', 'a') == 0
assert frequency('texts', 's') == 1
assert frequency('texts', 't') == 2
# limit tests
assert frequency('ttt', 't') == 3
assert frequency('', 'x') == 0
print('test_frequency: ok')
test_frequency()
frequency(x = input("Enter a word: "), y = input("Enter a letter(symbol): "))
这个小问题是函数打印它的值,而不是 returning 它们。
Python 有一些相当可疑的行为 returning None
每当函数结束时没有 return 语句导致此类不幸的错误。
解决方案是在 return a.count(y)
而不是 print(a.count(y))
结束。
这是因为您的函数正在打印值而不是返回计数。
def frequency(x, y):
a = list(x)
return a.count(y)
def test_frequency():
# Tests
assert frequency('texts', 'e') == 1
assert frequency('texts', 'a') == 0
assert frequency('texts', 's') == 1
assert frequency('texts', 't') == 2
# limit tests
assert frequency('ttt', 't') == 3
assert frequency('', 'x') == 0
print('test_frequency: ok')
test_frequency()
frequency(x = input("Enter a word: "), y = input("Enter a letter(symbol): "))