Python,函数改变值

标签 python

所以我无法让这个系统正常工作,我不能确定我问的是正确的问题,但这是正在发生的事情和我想要发生的事情。

money = 1
def Stats():
     print
     print "money " + str(money)

def gainM():
     money + 2
     Stats()

if money == 1:
     gainM()

现在去印钱时会发生什么,即使我将值加 2,值仍然是 1。 (代码不是我实际程序的副本,而是显示正在发生的事情的示例。)

最佳答案

money + 2 是空操作。您实际上必须将 money 分配给一个新值

money = money + 2
# or
money += 2

但是你会发现你得到一个错误 - 你不能分配给函数范围之外的变量。您可以使用 global 关键字:

global money
money += 2

这将允许您在函数内更改 money 的值。

但是,推荐的方法是将 money 作为参数传递:

def gainM(money):
    money += 2
    Stats()
    return money

if money == 1:
    money = gainM(money)

如果您使用的是第二个选项(您应该这样做),您还需要更改您的 Stats 函数,使其也有一个 money 参数。

def Stats(money):
     print
     print "money " + str(money)

否则该函数将打印 1 而不是 3

另一个建议 - 使用字符串格式。

'money %d' % money  # the old way
'money {}'.format(money)  # the new and recommended way

现在您将 money 传递给 Stats 函数。

def gainM(money):
    money += 2
    Stats(money)
    return money

关于Python,函数改变值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15035923/

相关文章:

Azure DevOps 中的 Python pytest - ModuleNotFoundError : No module named 'core'

python - 如何使用两个列表作为循环 python

Python nosetests 跳过某些测试

python - 逆小波变换[/xpost信号处理]

python - 如何将日期信息附加到 read_csv 上的时间列

python - 什么是 R 中不同颜色的 "good"调色板? (或 : can viridis and magma be combined together? )

python - 在 Flask 应用 Nose 测试中检查 Flash 消息

python - Selenium iframe 数据问题 - python

python - 使用 python 将匹配行批量追加到 csv 文件

python - setup.py 有问题