You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python 3.6 f-string实现99瓶啤酒时,如何在字符串中递减变量?

解决99瓶啤酒程序的f-string与循环问题

嘿,我来帮你搞定这个问题!你的代码里有两个关键问题需要修正:

1. 循环里的return导致只执行一次

你在for循环内部直接用了return,这会让函数在第一次循环(也就是i=10的时候)就直接返回结果,后面的循环根本没机会运行。如果你是想打印每一段歌词,应该用print()替代return;要是想收集所有歌词再返回,那得先把每段存到列表里,最后再返回整个列表。

2. f-string里的变量递减方式错误

你尝试用i-=1是赋值操作,f-string的占位符里只能放表达式,不能放赋值语句。直接用{i-1}就能得到当前i减1后的值啦,不需要修改i本身。

基础修正后的代码

先给你一个能正常运行的基础版本:

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

优化:处理单数"bottle"的情况

不过原版歌词里最后一瓶的时候是单数形式,我们可以再优化一下,让输出更准确:

def ninety_nine_bottles(): 
    for i in range(10, 0, -1): 
        current_bottles = f"{i} bottle{'s' if i != 1 else ''}"
        next_bottles = f"{i-1} bottle{'s' if i-1 != 1 else ''}" if i > 1 else "no more bottles"
        print(f'{current_bottles} of beer on the wall, {current_bottles} of beer! You take one down, pass it around, {next_bottles} of beer on the wall')

这样运行后,当i=1的时候,会输出正确的单数形式,最后还会显示"no more bottles",更贴合原版歌词~

内容的提问来源于stack exchange,提问作者DeltaFlyer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:29:40