Python单元测试非类型名称错误
我在这里的unittest中搜索了大量的NameError问题,但似乎找不到任何与我的问题相关的东西 这是一个家庭作业,所以如果你能告诉我哪里出了问题,而不是如何纠正,那就太好了。我试图为一个函数编写一个单元测试,该函数将列表中的最后一个数字与列表中的第一个数字交换 以下是我为函数编写的代码:Python单元测试非类型名称错误,python,unit-testing,nonetype,Python,Unit Testing,Nonetype,我在这里的unittest中搜索了大量的NameError问题,但似乎找不到任何与我的问题相关的东西 这是一个家庭作业,所以如果你能告诉我哪里出了问题,而不是如何纠正,那就太好了。我试图为一个函数编写一个单元测试,该函数将列表中的最后一个数字与列表中的第一个数字交换 以下是我为函数编写的代码: def swap_k(L, k): """ (list, int) -> NoneType Precondtion: 0 <= k <= len(L) // 2
def swap_k(L, k):
""" (list, int) -> NoneType
Precondtion: 0 <= k <= len(L) // 2
Swap the first k items of L with the last k items of L.
>>> nums = [1, 2, 3, 4, 5, 6]
>>> swap_k(nums, 2)
>>> nums
[5, 6, 3, 4, 1, 2]
>>> nums = [1, 2, 3, 4, 5, 6]
>>> swap_k(nums, 3)
>>> nums
[4, 5, 6, 1, 2, 3]
"""
L[:k], L[-k:] = L[-k:], L[:k]
这是错误消息:
E
======================================================================
ERROR: test_swapk_1 (__main__.TestSwapK)
Swap the first k items of L with the last k items of L. Where L =
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\xxxxx\xxxxxxxxxx\xxxxxxxxxxxx\test_swap_k.py", line 13, in test_swapk_1
a1.swap_k(L, k)
NameError: global name 'k' is not defined
----------------------------------------------------------------------
Ran 1 test in 0.016s
FAILED (errors=1)`
谁能告诉我哪里出了问题,我快疯了。同样,如果可以在不告诉我答案的情况下告诉我哪里出了问题,请这样做。错误非常清楚:
k
没有定义。在您的doctest示例中,k
是3
:
a1.swap_k(L, k=3)
我只是用
k=3
来表示详细。如果需要,可以使用a1.swap_k(L,3)。您尚未在函数中定义变量k
而不是:
a1.swap_k(L, k)
您可能想键入:
a1.swap_k(L, 2)
或
或者类似的东西。我应该知道我遗漏了这么简单的东西,谢谢你花时间回答。对Python非常陌生,以前从未出现过名称错误
a1.swap_k(L, 2)
k = 2
a1.swap_k(L, k)