简体   繁体   English

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

[英]Why is Python compiling this code without throwing errors?

I'm new to Python, so please bear with me.我是 Python 的新手,所以请多多包涵。 Why isn't Python throwing an error when it compiles the following code.为什么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

Wondering how there's no error even though 'nums' isn't defined, and neither is 'whatever', nor 'target'.想知道即使没有定义“nums”,也没有定义“whatever”和“target”,如何没有错误。

Thanks!谢谢!

Global variables are looked up at runtime, when the function tries to access their value, not when the function is defined.全局变量在运行时查找,当 function 尝试访问它们的值时,而不是在定义 function 时。 If there's still no nums variable when the function tries to actually use it, you'll get a NameError at that point, but not at function definition time.如果在 function 尝试实际使用它时仍然没有nums变量,那么此时您将收到 NameError ,但在 function 定义时不会。

The process here isn't "look up nums and compile bytecode using the information we found";这里的过程不是“使用我们找到的信息查找nums并编译字节码”; it's "compile bytecode that, if run, might look up nums then".它是“编译字节码,如果运行,则可能会查找nums ”。

From the code you provided, looks like you're not running the function, therefore the code is not being executed and it doesn't use the non-existing variables.从您提供的代码来看,您似乎没有运行 function,因此代码没有被执行并且它不使用不存在的变量。

Once you declared the function, if you try to call it, you'll find this errors:一旦你声明了 function,如果你尝试调用它,你会发现这个错误:

>>> 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM