【问题标题】:Altering variable's value in a function by calling another function as a subfunction通过调用另一个函数作为子函数来改变函数中变量的值
【发布时间】:2017-11-08 23:11:21
【问题描述】:
def tim():
    cash = 100
    while cash != 0:
        print("while loop:",cash)
        john(cash)

def john(cash):
    print("john func:",cash)
    cash = cash -1

tim()

有人能解释一下为什么 john() 不会降低现金​​的价值吗?我已经为此苦苦挣扎了很长时间。

【问题讨论】:

  • 因为cash是一个局部变量,你为什么要这样做?
  • @JimFasarakisHilliard 我正在编写一个投注游戏,其中现金在增加或减少,但仍然不是 0。我应该如何实现?
  • 好吧,你为什么需要一个额外的函数来做增加和减少?
  • @JimFasarakisHilliard 我认为函数的代码太长是不好的做法,所以我写了另一个函数在其中调用
  • 嗯,当然,但你把它发挥到了极致。只需在tim 中使用cash。

标签: python python-3.x function loops while-loop


【解决方案1】:

函数参数是按值传递的,而不是按引用传递的,所以赋值给john中的变量对tim中的变量没有影响。该函数应返回新值:

def tim():
    cash = 100
    while cash != 0:
        print("while loop:",cash)
        cash = john(cash)

def john(cash):
    print("john func:",cash)
    return cash - 1

tim()

【讨论】:

    猜你喜欢
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    相关资源
    最近更新 更多