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!

5
  • I was certain this would be a duplicate, but I can't find one. Commented Mar 29, 2021 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? Commented Mar 29, 2021 at 10:24
  • @KarlKnechtel - It's just scoping rules. I'm not sure why it's such a revelation for everyone. Commented Mar 29, 2021 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. Commented Mar 29, 2021 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.) Commented Mar 29, 2021 at 10:29

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

That helps, thank you. Coming from a Java background, this startled me for a minute.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.