gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:10:48 25 4
gpt4 key购买 nike

我正在尝试使用 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')

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

最佳答案

你正在那里寻找 {i - 1}i -= 1 是 f 字符串中不允许的语句。

除此之外,你不应该从你的函数中返回;这只会导致 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')

关于Python:如何使用 f 字符串进行数学运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49344643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com