Del*_*yer 1 python python-3.6 f-string
我正在尝试使用 python 3.6 的新 f-string 功能在墙上编写自己的 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')
Run Code Online (Sandbox Code Playgroud)
如何减少最后一对括号中的“i”?我试过 i-=1 无济于事(语法错误)...
你正在{i - 1}那里寻找。i -= 1是 f 字符串中不允许的语句。
除此之外,你不应该从你的函数中返回;这导致仅for执行循环的第一次迭代。相反,要么print创建一个字符串列表并加入它们。
最后,考虑将瓶子的起始值传递给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')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1896 次 |
| 最近记录: |