Py学习  »  Python

Python 3.7 builtins.NameError

Artem Pankratov • 4 年前 • 818 次点击  

现在我正在学习一些基本的东西,比如list等等,但是我在编写代码时遇到了一个问题:

from typing import List


def greatest_difference(nums1: List[int], nums2: List[int]) -> int:
    """Return the greatest absolute difference between numbers at
    corresponding positions in nums1 and nums2.

    Precondition: len(nums1) == len(nums2) and nums1 != []

    >>> greatest_difference([1, 2, 3], [6, 8, 10])
    7
    >>> greatest_difference([1, -2, 3], [-6, 8, 10])
    10
    """
difference = 0
diff_over_term = 0
for i in range(len(nums1)):
    diff_over_term = abs(nums1[i] - nums2[i])
if diff_over_term > difference:
        difference = diff_over_term
print(difference)

因为某些原因,它说

builtins.NameError:名称 nums1 未定义

我试着玩缩进游戏,但没用。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/51962
 
818 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Dan
Reply   •   1 楼
Dan    4 年前

看起来您没有缩进函数的内容。试试这个:

from typing import List


def greatest_difference(nums1: List[int], nums2: List[int]) -> int:
    """Return the greatest absolute difference between numbers at
    corresponding positions in nums1 and nums2.

    Precondition: len(nums1) == len(nums2) and nums1 != []

    >>> greatest_difference([1, 2, 3], [6, 8, 10])
    7
    >>> greatest_difference([1, -2, 3], [-6, 8, 10])
    10
    """
    difference = 0
    diff_over_term = 0
    for i in range(len(nums1)):
        diff_over_term = abs(nums1[i] - nums2[i])
    if diff_over_term > difference:
        difference = diff_over_term
    return difference

# and now call your function, notice how these lines aren't indented, that means they are not part of the function definition
list_a = [1, 2, 3]
list_b = [6, 8, 10]
print(greatest_difference(list_a, list_b)