为什么 Python 编译这段代码没有抛出错误?

Why is Python compiling this code without throwing errors?

我是 Python 的新手,所以请多多包涵。 为什么 Python 在编译以下代码时不抛出错误。

def b_search(left, right):
    while left <= right:
        mid = left + (right-left)//2

        if nums[mid] == target:
            return mid
        if nums[mid] < target:
            left = whatever
        else:
            right = mid-1
    return -1

想知道为什么 'nums' 没有定义,'whatever' 也没有错误,'target'.

谢谢!

全局变量在 运行 函数尝试访问它们的值时查找,而不是在定义函数时查找。如果在函数尝试实际使用它时仍然没有 nums 变量,您将在此时得到一个 NameError,但不会在函数定义时得到。

这里的过程不是“查找 nums 并使用我们找到的信息编译字节码”;它是“编译字节码,如果 运行,可能会查找 nums”。

从您提供的代码来看,您似乎不是 运行 函数,因此代码没有被执行,也没有使用不存在的变量。

一旦你声明了这个函数,如果你试图调用它,你会发现这个错误:

>>> b_search(3,9)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in b_search
NameError: name 'nums' is not defined