Python函数参数值传递
生活随笔
收集整理的這篇文章主要介紹了
Python函数参数值传递
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Python的函數參數是通過值傳遞的,但是如果變量是可變對象,返回到調用程序后,該對象會呈現(xiàn)被修改后的狀態(tài)
測試程序如下:
# 值傳遞不改變變量 def addInterest(balance, rate):newBalance = balance * (1+rate)return newBalance def test():amount = 1000rate = 0.5addInterest(amount, rate)print(amount)test() 運行結果如下: Connected to pydev debugger (build 143.1559) 1000Process finished with exit code 0可以發(fā)現(xiàn)沒有改變變量amount的值,但是我們如果傳遞的是列表對象,測試程序如下:
# 傳遞列表變量,會改變列表的值 def addInterest(balances, rate):for i in range(len(balances)):balances[i] = balances[i] * (1+rate) def test():amounts = [1000, 105, 45, 739]rate = 0.05addInterest(amounts, rate)print(amounts)test() 運行結果如下: Connected to pydev debugger (build 143.1559) [1050.0, 110.25, 47.25, 775.95]Process finished with exit code 0我們會發(fā)現(xiàn)函數操作改變了列表對象的值
總結
以上是生活随笔為你收集整理的Python函数参数值传递的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MFC制作计算器
- 下一篇: Python学习笔记(数据类型)