多次打印函数

2024-05-08 20:14:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,在打印将要打印的函数时遇到了问题:

"99 bottles of beer on the wall 99 bottles of beer Take one down and pass it around, 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one down and pass it around, 97 bottles of beer on the wall 97 bottles of beer on the wall 97 bottles of beer Take one down and pass it around, 96 bottles of beer on the wall"

这是我的密码:

def sing(number):
    number = 99
    print(number, "bottles of beer on the wall", number, "bottles of beer")
    print("Take one down and pass it around, ", end='')
    number -= 1
    print(number, "bottles of beer on the wall")
    return number

print(sing(sing(sing(number))))

有人能帮我找出哪里出了问题吗?非常感谢。你知道吗

谢谢


Tags: andofthenumberonitpassone
2条回答

编写代码时的问题是,每次调用函数时都要重新定义number,而不是使用传入的值。只需删除函数的第一行就可以修复它,并且可以删除最后一行print

def sing(number):
    print(number, "bottles of beer on the wall", number, "bottles of beer")
    print("Take one down and pass it around, ", end='')
    number -= 1
    print(number, "bottles of beer on the wall")
    return number

sing(sing(sing(99)))

为什么不使用循环?您可以使用rangenumber99退到1。你知道吗

def sing(number):
    print(number, "bottles of beer on the wall", number, "bottles of beer")
    print("Take one down and pass it around, ", end='')
    print(number-1, "bottles of beer on the wall")

for number in range(99, 0, -1):
    sing(number)

否则,可以在函数本身中添加循环

def sing(number):
    while number > 1:
        print(number, "bottles of beer on the wall", number, "bottles of beer")
        print("Take one down and pass it around, ", end='')
        number -= 1
        print(number, "bottles of beer on the wall")

sing(99)

相关问题 更多 >