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

标签 python compiler-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”。

关于python - 为什么 Python 编译这段代码没有抛出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66852331/

相关文章:

python - 类型错误 : only length-1 arrays can be converted to Python scalars with NUMPY

python - 使用 Factoradic 系统允许重复时查找第 K 个字典排列

java - 当 if 条件为常量时,为什么无法检测到无法访问的代码?

maven - 执行失败 : 'control build' & Failed to execute goal: maven-compiler

c++ - 将 shared_ptr 与指向指针的指针一起使用时出现编译器错误

python - 梯度提升树库

python - PIL ImageGrab 在 VirtualBox 的第二个虚拟监视器上失败

python - 在 Python 中延迟初始化的字符串

npm - Electron抛出了编译错误,并且Windows命令提示符变为不可写

c++ - 错误 : Expected a Type Specifier. C++ 继承