如果我有这个:
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=" ")
我之前定义 lists
,所以 oneFunction(lists)
完美运行。
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
总是一样的,即使我打电话给 oneFunction(lists)
。
我希望能够,每次调用第一个函数然后调用第二个函数时,都有不同的 word
。
我可以不在 word
之外定义 oneFunction(lists)
吗?
原文由 JNat 发布,翻译遵循 CC BY-SA 4.0 许可协议
One approach would be to make
oneFunction
return the word so that you can useoneFunction
instead ofword
inanotherFunction
:另一种方法是制作
anotherFunction
接受word
作为参数,您可以从调用结果中传递oneFunction
:最后,您可以在类中定义这两个函数,并使
word
成为成员:创建类后,您必须实例化一个实例并访问成员函数: