这里我写了两个简单的程序,并期望结果是相同的: 程序1(结果=123):
price=[]
def checkCondition(a,b):
if a<b:
price.append(123)
if __name__ == '__main__':
checkCondition(1,2)
print price[0]
程序 2(结果=''):
price=''
def checkCondition(a,b):
if a<b:
price=123
if __name__ == '__main__':
checkCondition(1,2)
print price
为什么它无法将 123 分配给程序 2 中的价格?
最佳答案
您正在分配一个局部变量。告诉 Python 使用全局变量:
price=''
def checkCondition(a,b):
global price # now reassigning price
if a<b:
price=123
if __name__ == '__main__':
checkCondition(1,2)
print price
来自 Python 文档 Naming and binding :
If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block. [...]
If the global statement occurs within a block, all uses of the name specified in the statement refer to the binding of that name in the top-level namespace.
关于python - 关于Python中的变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30809770/