2

I got an error at the while, that the name 'start' is not defined, although I declared it as global inside the nested one, I know that there is another approach is to changed the signature of the function of BS to take the start and end variables, but I need to know how to solve it using the global approach, Thanks!

class math:
    def search(self,nums,x):
        start = 0
        end = len(nums)

        def BS():
            global start
            global end

            while(start<=end):
                #i assign  here  a new value to start and end

        first = BS()
        return first
0

1 Answer 1

5

Use nonlocal, so something like:

class math:
    def search(self,nums,x):
        start = 0
        end = len(nums)

        def BS():
            nonlocal start
            nonlocal end

            while(start<=end):
                pass # use pass if you want to leave it empty!
                #i assign  here  a new value to start and end

        first = BS()
        return first

Maybe you'll find this helpful!

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

4 Comments

Exactly. @Flupper, the reason this works is because, when you first defined start, Python treated it as local to the search function. When, in the BS function, you declared global start, Python assumed that this must be a different variable from the previous instance of start because that one wasn't global.
Thank you guys, finally got it, it took me some time to know this reason.
@Flupper Do you mind accepting the answer if it helps! Thanks
I immediately accepted it after you submitted the answer, but I got an error message that I should wait more time to accept it, then I forgot, thank you for remembering me it!

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.