You are incrementing a temporary variable x in the function namespace, therefore col is not modified. If you want to change col you can:
- use a
class with a classmethod and a class attribute - use a decorator as in Paul Panzer's answer
- return the value of
x and affect it to col - use a
global statement.
If you are unfamiliar with namespace check this link
First using a class with a classmethod and a class attribute:
class functions: col = 0 @classmethod def function1(cls, mylists): row=1 for elm in mylists: ws.write(row, cls.col,elm) row+=1 cls.col += 1 functions.function1(mylist1) functions.function1(mylist2) functions.function1(mylist3)
This would be my preferred option as the namespaces are not polluted and the code is cleaner than with returning a value.
Now returning a value:
def funtion1(mylists,x): row=1 for elm in whichlist: ws.write(row,x,elm) row=row+1 return x + 1 col = 0 col = function1(mylist1,col) col = function1(mylist2,col) col = function1(mylist3,col)
Or with a global:
def function1(mylists): global col row=1 for elm in mylists: ws.write(row,col,elm) row+=1 col += 1 col=0 function1(mylist1) function1(mylist2) function1(mylist3)
xis local to the function, and changing it does not affect the value ofcol. If it was a mutable object, and you changed a member value within the function - you would see your expected behaviour.