Nightviz1on
Nightviz1on

Reputation: 21

Python - for loop ignoring if statement

I'm attempting to write a Python program that will print out the lyrics of 99 Bottles of Beer in chunks, which I've gotten to work. However, I need the last line to say "1 bottle of beer" as opposed to "1 bottles of beer".

I wrapped my code in an if statement, but it appears the if statement is getting ignored. What am I doing wrong?

verse = '''
{some} bottles of beer on the wall
{some} bottles of beer
Take one down, pass it around
{less} bottles of beer on the wall
'''

verse2 = '''
{some} bottles of beer on the wall
{some} bottles of beer
Take one down, pass it around
1 bottle of beer on the wall
'''

for bottles in range(99 , 1, -1):
  if bottles >= 2:
    print(verse.format(some = bottles, less = bottles - 1))
  else:
    print(verse2.format(some = bottles))

Upvotes: 0

Views: 122

Answers (2)

Philip Tzou
Philip Tzou

Reputation: 6468

Try this:

print(list(range(99 , 1, -1)))

The result should be:

[99, 98, 97, ..., 5, 4, 3, 2]

Number 1 never appeared.

To Fix this issue, simply changing range(99, 1, -1) to range(99, 0, -1).

Upvotes: 2

wim
wim

Reputation: 363616

Ranges don't include the endpoint, so the final element of your range is not 1 but 2.

Should you change the if-statement to if bottles > 2: instead, the output will be correct.

Upvotes: 1

Related Questions