[英]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字符串中不允許的語句。
除此之外,您不應該從函數中返回。 這只會導致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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.