Skip to content

Instantly share code, notes, and snippets.

@TheMuellenator
Created January 14, 2020 11:47
Show Gist options
  • Save TheMuellenator/a36e7edadcf4b38aff1d759dad737526 to your computer and use it in GitHub Desktop.
Save TheMuellenator/a36e7edadcf4b38aff1d759dad737526 to your computer and use it in GitHub Desktop.
Python Loops Coding Exercise Solution
def sing(num_bottles):
#TODO: Add your code to achieve the desired output and pass the challenge.
#NOTE: The f String method of String Interpolation does not work.
lyrics = []
for num in range(num_bottles, 0, -1):
lyrics.append('{num} bottles of beer on the wall, {num} bottles of beer.'.format(num = num))
lyrics.append('Take one down and pass it around, {num} bottles of beer on the wall.'.format(num = num - 1))
lyrics.append('')
return lyrics
@nsharma73
Copy link

nsharma73 commented May 10, 2021

Here is an alternative

def sing(num_bottles):
        counter=num_bottles
        while counter > 0:
             print(counter,' bottles of beer on the wall, ', counter, 'bottles of beer')
             print('Take one down and pass it around, ', counter-1, 'bottles of beer on the wall')
             counter = counter -1

@CarlenePSF
Copy link

Here is another alternative

def sing(num_bottles):
    lirics = []
    for n in range(0, num_bottles, 1):
        if num_bottles - n == 0:
            break
        lirics.append(f'{num_bottles - n} bottles of beer on the wall. {num_bottles - n} bottles of beer')
        lirics.append(f'Take one down and pass it around, {num_bottles - n-1} bottles of beer on the wall')
        lirics.append('')

    return lirics

@ruben-ghidanac
Copy link

I don't understand the notation with curly braces why we need them and how it works,

why we need to use syntax .format(num = num)

why we need to specifiy .format(num = num -1) to decrease with -1,

why is not enough to have only in function range() the third parameter which his purpose is exactly to specify increment/decrement step

@Cynosure11
Copy link

I've got issue with exercise 6. My answer was correct and still saying wrong...

@alarv
Copy link

alarv commented Sep 12, 2022

Here's another example that's a bit simpler:

def sing(num_bottles):
    output = []
    for n in reversed(range(num_bottles + 1)):
        if(n == 0) :
            break;
        output.append('{} bottles of beer on the wall, {} bottles of beer.'.format(n, n))
        output.append('Take one down and pass it around, {} bottles of beer on the wall.'.format(n - 1))
        output.append('');
        
    return output

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment