if I have this:
def oneFunction(lists):
category=random.choice(list(lists.keys()))
word=random.choice(lists[category])
def anotherFunction():
for letter in word: #problem is here
print("_",end=" ")
I have previously defined lists
, so oneFunction(lists)
works perfectly.
My problem is calling word
in line 6. I have tried to define word
outside the first function with the same word=random.choice(lists[category])
definition, but that makes word
always the same, even if I call oneFunction(lists)
.
I want to be able to, every time I call the first function and then the second, have a different word
.
Can I do this without defining that word
outside the oneFunction(lists)
?
The simplest option is to use a global variable. Then create a function that gets the current word.
current_word = ''
def oneFunction(lists):
global current_word
word=random.choice(lists[category])
current_word = word
def anotherFunction():
for letter in get_word():
print("_",end=" ")
def get_word():
return current_word
The advantage of this is that maybe your functions are in different modules and need to access the variable.
def oneFunction(lists):
category=random.choice(list(lists.keys()))
word=random.choice(lists[category])
return word
def anotherFunction():
for letter in word:
print("_",end=" ")
def anotherFunction(word):
for letter in word:
print("_", end=" ")
def oneFunction(lists):
category = random.choice(list(lists.keys()))
word = random.choice(lists[category])
return anotherFunction(word)
Everything in python is considered as object so functions are also objects. So you can use this method as well.
def fun1():
fun1.var = 100
print(fun1.var)
def fun2():
print(fun1.var)
fun1()
fun2()
print(fun1.var)
Source: Stackoverflow.com