具有多个参数的简单函数Python 2.7

时间:2013-01-26 11:25:48

标签: python function

我正在学习Zelle的Python编程,并且在函数上遇到了一些问题。

我们得到了这个:

def addInterest(balance, rate):
    newBalance = balance * (1+rate)
    balance = newBalance

def test(): 
    amount = 1000
    rate = 0.05
    addInterest(amount, rate)
    print amount

test()

此代码无法打印1050作为输出。但以下成功:

def addInterest(balance, rate):
    newBalance = balance * (1+rate)
    return newBalance

def test():
    amount = 1000
    rate = 0.05
    amount = addInterest(amount, rate)
    print amount

test() 

微妙的区别在于 addInterest 函数的第3行。 Zelle解释了这一点,但我还没有掌握它。你能解释为什么#1代码 - 几乎是完美的 - 不会做#2的做法?

3 个答案:

答案 0 :(得分:3)

这是因为您在balance中修改的addInterest对象与传递给函数的amount对象不同。简而言之,您修改了传递给函数的对象的本地副本,因此原始对象的值保持不变。如果在python shell中运行以下代码,则可以看到它:

>>> def addInterest(balance, rate):
...     print (balance)
...     newBalance = balance * (1 + rate)
...     balance = newBalance
... 
>>> amount = 1000
>>> rate = 0.05
>>> print id(amount)
26799216
>>> addInterest(amount, rate)
1000
>>> 

id函数返回一个对象的标识,可用于测试两个对象是否相同。

答案 1 :(得分:0)

关键词是return。返回用于将函数中的值返回到变量(在第二个代码中,变量为amount)。

在#1中你没有返回任何东西,这就是print amount不是你想要的原因。

在您的第二个代码中,您是returning newBalance的值。变量amount现在与函数中的newBalance值相同。

因此,在您的第一个代码中,addInterest(amount, rate)无效。它没有返回任何东西,所以没有用。但是你在第二个函数中所做的是正确的。

答案 2 :(得分:0)

How do I pass a variable by reference?

上查看漂亮的答案
    self.variable = 'Original'
    self.Change(self.variable)

def Change(self, var):
    var = 'Changed'