Python:如何使用 f 字符串进行数学运算

Python: How to do math using f-string

我正在尝试使用 python 3.6 的新 f 弦功能在墙上编写我自己的 99 瓶啤酒的实现,但我被卡住了:

def ninety_nine_bottles():
    for i in range(10, 0, -1):
        return (f'{i} bottles of beer on the wall, {i} of beer! You take one down, pass it around, {} bottles of beer on the wall')

如何减少最后一对括号中的 'i'?我试过 i-=1 无济于事(语法错误)...

您正在那里寻找 {i - 1}i -= 1 是 f-strings 中不允许的语句。

除此之外,您不应该 return 从您的函数中;结果只执行 for 循环的第一次迭代。相反,print 或创建一个字符串列表并加入它们。

最后,考虑将 bottles 的起始值传递给 ninety_nine_bottles

总而言之,使用如下:

def ninety_nine_bottles(n=99):
    for i in range(n, 0, -1):
        print(f'{i} bottles of beer on the wall, {i} of beer! You take one down, pass it around, {i-1} bottles of beer on the wall')