Search code examples
pythonvariablesgspread

While loop modify global variable


I thought loops in python do not change our global variables; however, the code below gives 10 as a result. Can someone explain what is happening here?

source_col_numbers = 9
i = 1
columns = {}

while i <= source_col_numbers:
    columns[i] = list(filter(None , source.sheet1.col_values(i)))
    i += 1

print(i)

Solution

  • You have declared i as a global variable and then you are using it in the loop. So, whatever changes you make to i in your program will be applied on that i since it's a global variable.

    Global variable means i has a global scope. If you had created i inside a function, it would have a local scope and could not be accessed outside of the function.

    So in your case, changes will be made and output will be 10.