我正在编写一个简单的程序,将歌词写在墙上的99瓶啤酒上。但是,当我在while循环内调用该函数时,我编写的从bottleNum中减去一个的函数不起作用。我不确定我在这里做了什么?我不应该能够在while循环内调用函数吗?运行代码时没有出现错误,一遍又一遍地打印文本,并且bottleNum始终等于99。
#pragma comment(lib, "MyLib.lib")
答案 0 :(得分:4)
如果您这样做,它将起作用:
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))
答案 1 :(得分: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))
之所以不起作用,是因为调用该函数时,您没有返回任何值,而您所做的只是提供了一个引用。