Local vs Global Variables

Hi there,

Below is a snippet of my code from the DQ mission on Binary search. A question came across my mind while writing the code below relating to global and local variables. Specifically, since the lower/upper bound variable are modified within the while loop, are they not consider local variables only and shouldn’t change the global variables outside the loop but still in the function?

Many thanks in advance!

def player_age(name):
    name = format_name(name)
    upper_bound = length - 1
    lower_bound = 0
    index = math.floor((upper_bound + lower_bound) / 2)
    guess = format_name(nba[index][0])
    while guess != name and lower_bound < upper_bound:
        if name < guess:
            upper_bound = index - 1
        elif name > guess:
            lower_bound = index + 1
        index = math.floor((upper_bound + lower_bound)/2)
        guess = format_name(nba[index][0])
    if guess == name:
        return nba[index][2]
    else:
        return -1

I’m not sure I understand the question, but loops do not interact with variable “locality” in the same way that functions do.

Here’s a simple example:

>>> y = 17
>>> for x in range(3):
...     y = -x
...     print(x,y)
... 
0 0
1 -1
2 -2

At the end of the loop, the variable name x was assigned the value 2, and y was assigned -2. These variables are still accessible and have these values after the loop:

>>> print(x,y)
2 -2

Note that y didn’t keep the value 17 assigned outside of the loop. A variable defined in a for a loop has the same degree of locality than a variable defined outside of it.

I hope this helps.

Thanks, Bruno.

Going back to my original code, you will see that there is a guess variable both inside and outside the while loop. In the subsequent if loop that is outside the while loop, the guess variable retains its value calculated in the while loop - it appears that that while loop has modified the guess variable that was defined previously outside the loop

However, I can understand how the for loop in your example does not modified the value of the global y variable that was defined outside the loop. Hence I am confused why it doesn’t happen the same way in a while loop.

Many thanks for your help

You got this wrong, it does change the value of y. Note that in the example I posted I’m printing y with every iteration, and I’m also printing it after the loop and it doesn’t retain the original value anymore.