DeltaFlyer
DeltaFlyer

Reputation: 471

Python: How to do math using f-string

I'm attempting to write my own implementation of 99 bottles of beer on the wall using python 3.6's new f-string feature, but I'm stuck:

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')

How do I decrement 'i' in the last pair of brackets? I've tried i-=1 to no avail (syntax error)...

Upvotes: 2

Views: 8489

Answers (1)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160407

You're looking for {i - 1} there. i -= 1 is a statement which isn't allowed in f-strings.

In addition to that, you shouldn't return from your function; that results in only the first iteration of the for loop executing. Instead, either print or create a list out the strings and join them.

Finally, consider passing around the starting value of bottles to ninety_nine_bottles.

All in all, use the following:

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')

Upvotes: 8

Related Questions