python - 关于Python中的变量赋值

标签 python

这里我写了两个简单的程序,并期望结果是相同的: 程序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/

相关文章:

python - 交错 numpy 矩阵的行,生成排列方案

python - 如何在 ptpython 控制台中读取历史记录?

python - 将 lambda 函数应用于 pandas 数据框 - 返回索引但不返回值?

python - 自动将一些文本附加到每条日志消息

python - 如何使用Python API为应用服务上传和配置SSL证书

python - Flask-Admin 具有多对多关系中的附加字段

python - 这个变量 `instantiated` 的范围是什么

python - 从 Jupyter Notebook 显示和保存 PGF 图

python - Windows 7 上的 GetWindowRect 太小

python - 如何使用 python re 模块在字符串中自动查找类似 'c++' 的模式?