【问题标题】:Unable to call a function while inside of a while loop在while循环内无法调用函数
【发布时间】:2020-06-22 08:07:06
【问题描述】:

我正在编写一个简单的程序,它可以在墙上写出 99 瓶啤酒的歌词。但是,当我在 while 循环中调用它时,我编写的从 BottleNum 中减一的函数不起作用。我不确定我在这里做了什么?我不应该能够在while循环中调用函数吗?运行代码时没有出现错误,文本反复打印,bottlesNum 始终等于 99。

bottlesNum = 99

def bottle_subtraction(bottles):
    bottles = bottles - 1

while bottlesNum > 0:
    if bottlesNum != 1:
        print("{x} bottles of beer on the wall, {x} bottles of beer".format(x = bottlesNum))
    elif bottlesNum == 1:
        print("{x} bottle of beer on the wall, {x} bottle of beer".format(x = bottlesNum))

    bottle_subtraction(bottlesNum)

    print("Take one down and pass it around, {} bottles of beer on the wall".format(bottlesNum))

【问题讨论】:

  • "难道我不能在 while 循环中调用函数吗?"你确实在调用它。但是,我不确定您为什么希望调用它会影响全局 bottlesNum
  • 你的函数基本上什么都不做,你只是将bottle - 1的结果分配给一个局部变量
  • 你在用python 3吗?

标签: python function while-loop


【解决方案1】:

如果你这样做,它会起作用:

bottlesNum = 99

def bottle_subtraction(bottles):
    bottles = bottles - 1
    return bottles # we return the updated value here

while bottlesNum > 0:
    if bottlesNum != 1:
        print("{x} bottles of beer on the wall, {x} bottles of beer".format(x = bottlesNum))
    elif bottlesNum == 1:
        print("{x} bottle of beer on the wall, {x} bottle of beer".format(x = bottlesNum))

    bottlesNum = bottle_subtraction(bottlesNum) # we store the updated variable

    print("Take one down and pass it around, {} bottles of beer on the wall".format(bottlesNum))

【讨论】:

  • 谢谢!你能告诉我为什么我的不工作吗?代码现在可以工作,但我不确定我是怎么出错的。
  • @saeley 该值在函数内部得到了更新,但是因为您从未返回它并将其存储回来,所以该更改从未反映在您的函数之外。我用一些 cmets 更新了我的答案。
  • 您的原始代码位于不同的范围内,因此您正在修改 function 中的瓶子,而不是全局瓶子。这发生在作业上。如果您使用 global bottlesNum 关键字,您可以告诉函数写入全局瓶子
【解决方案2】:

这应该可行:

bottlesNum = 99

def bottle_subtraction(bottles):
    bottles = bottles - 1
    return bottles

while bottlesNum > 0:
    if bottlesNum != 1:
        print("{x} bottles of beer on the wall, {x} bottles of beer".format(x = bottlesNum))
    elif bottlesNum == 1:
        print("{x} bottle of beer on the wall, {x} bottle of beer".format(x = bottlesNum))

    bottlesNum = bottle_subtraction(bottlesNum)

    print("Take one down and pass it around, {} bottles of beer on the wall".format(bottlesNum))

你的不起作用的原因是因为当你调用函数时,你没有返回任何值,你所做的只是提供一个参考。

【讨论】:

    猜你喜欢
    • 2017-11-24
    • 2020-06-16
    • 1970-01-01
    • 2020-03-17
    • 2015-12-28
    • 1970-01-01
    • 2015-07-13
    • 2015-07-26
    • 2016-04-30
    相关资源
    最近更新 更多