2

I'm new to Python, so please bear with me. Why isn't Python throwing an error when it compiles the following code.

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

Thanks!

svms54
  • 129
  • 1
  • 1
  • 9
  • I was certain this would be a duplicate, but I can't find one. – Karl Knechtel Mar 29 '21 at 10:22
  • Me neither, I posted this when I couldn't find a similar question. Surely people new to Python must've had this question before? – svms54 Mar 29 '21 at 10:24
  • @KarlKnechtel - It's just scoping rules. I'm not sure why it's such a revelation for everyone. – TigerhawkT3 Mar 29 '21 at 10:25
  • 2
    It's not "just scoping rules"; local vs. global is a separate issue from runtime vs compile-time name lookup. It's a revelation for many people because many other programming languages don't work the same way. – Karl Knechtel Mar 29 '21 at 10:27
  • Plus, local variables *are* resolved at bytecode compilation time in most cases. The difference between how globals are handled and how locals are (usually) handled can be confusing. (The primary cases where locals aren't resolved at compile time are with class scopes and `exec`.) – user2357112 Mar 29 '21 at 10:29

2 Answers2

5

Global variables are looked up at runtime, when the function tries to access their value, not when the function is defined. 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.

The process here isn't "look up nums and compile bytecode using the information we found"; it's "compile bytecode that, if run, might look up nums then".

user2357112
  • 260,549
  • 28
  • 431
  • 505
3

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.

Once you declared the function, if you try to call it, you'll find this errors:

>>> 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
Roger
  • 158
  • 8