我正在函数块内的全局列表上使用.pop方法,但全局列表正在块外更新。我认为局部变量不能修改全局变量。
This should not work, but it does:
import random
PhraseBank = ['a','b','c','d']
def getPuzzle(secretphrase):
phraseIndex = random.randint(0,len(PhraseBank)-1)
secretphrase = PhraseBank.pop(phraseIndex)
return secretphrase #Returns and item indexed from the PhraseBank
while len(PhraseBank) != 0:
secretphrase = getPuzzle(PhraseBank) #works
print(secretphrase, PhraseBank)
输出为:
a ['b', 'c', 'd']
d ['b', 'c']
c ['b']
b []
?
最佳答案
不能在函数内部为全局变量赋值(除非显式使用global
声明)。。