I’m creating a python script which prints out the whole song of ’99 bottles of beer’, but reversed. The only thing I cannot reverse is the numbers, being integers, not strings.
This is my full script,
JavaScript
x
18
18
1
def reverse(str):
2
return str[::-1]
3
4
def plural(word, b):
5
if b != 1:
6
return word + 's'
7
else:
8
return word
9
10
def line(b, ending):
11
print b or reverse('No more'), plural(reverse('bottle'), b), reverse(ending)
12
13
for i in range(99, 0, -1):
14
line(i, "of beer on the wall")
15
line(i, "of beer"
16
print reverse("Take one down, pass it around")
17
line(i-1, "of beer on the wall n")
18
I understand my reverse function takes a string as an argument, however I do not know how to take in an integer, or , how to reverse the integer later on in the script.
Advertisement
Answer
You are approaching this in quite an odd way. You already have a reversing function, so why not make line
just build the line the normal way around?
JavaScript
1
5
1
def line(bottles, ending):
2
return "{0} {1} {2}".format(bottles,
3
plural("bottle", bottles),
4
ending)
5
Which runs like:
JavaScript
1
3
1
>>> line(49, "of beer on the wall")
2
'49 bottles of beer on the wall'
3
Then pass the result to reverse
:
JavaScript
1
3
1
>>> reverse(line(49, "of beer on the wall"))
2
'llaw eht no reeb fo selttob 94'
3
This makes it much easier to test each part of the code separately and see what’s going on when you put it all together.