If you want the function itself to modify it's internal state, you can declare it globally.
But because in your case, e
makes sense only as an attribute of the function no
... why not making it just that, an attribute?
def no(paths: str):
for path in paths.split(" "):
print(" ItemListData(" + str(no.e) + ")=(ItemDefination=" + path + '")')
no.e += 1
no.e = 0
for example in ["example1", "example2"]:
no(example)
In this case, no.e
is also declared globally (and it could be accessed by other functions, e.g. print(no.e)
).
Note that because no
is declared (in it's own def
), you don't get UnboundLocalError
, even if no.e
wasn't yet declared, but you'll get AttributeError
if you forget to declare it before using it.
It may be considered and abuse of function attributes, but in my opinion it's justified here since it makes explicit that e
only has meaning as part of no
. But if you want a more explicit manipulation of global variables, you can also do
def no(paths: str):
global E
for path in paths.split(" "):
print(" ItemListData(" + str(E) + ")=(ItemDefination=" + path + '")')
E += 1
E = 0
while True:
paths = input()
no(paths)
As a side note, no
doens't seem to make sense outside a for
/while
loop since it's assuming the value e
needs to be updated. And your while
loop is doing little more than calling no
. Is it really necessary to dissociate these two?
You could just do
e = 0
while True:
paths = input()
for path in paths.split(" "):
print(" ItemListData(" + str(e) + ")=(ItemDefination=" + path + '")')
e = e + 1
(Or put all that inside a function)