变量范围(Python 新手) [英] Variable scope (Python Newbie)
本文介绍了变量范围(Python 新手)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在功能块内的全局列表上使用 .pop 方法,但全局列表正在块外更新.我认为局部变量不能修改全局变量.
I am using a .pop method on a Global list inside a function block, but the Global list is being updated outside the block. I thought that local variables can't modify Global variables.
这不应该工作,但确实有效:
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 []
为什么我只在功能块内修改 PhraseBank 会在全局范围内更新?
Why is PhraseBank getting updated Globally when I am only modifying it inside a function block?
推荐答案
你不能赋值给一个函数内的全局变量(除非你明确使用一个global
宣言).您可以很好地修改存储在全局变量中的对象.
You can't assign to a global variable inside a function (unless you explicitly use a global
declaration). You can modify objects stored in global variables just fine.
这篇关于变量范围(Python 新手)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文