[Courses] [python] Lesson 2: Loops, if, and beer

Peggy Russell prusselltechgroup at gmail.com
Mon Jun 27 06:01:52 UTC 2011


> ===================== Homework =======================
> 
> 1. Your first programming assignment!
>    Write a program for the old "bottles of beer" song. It should print
>    something like:
>    99 bottles of beer on the wall
>    98 bottles of beer on the wall
>    97 bottles of beer on the wall
>    ... all the way down to 1.
> 
>    Extra credit: make it print the number twice, e.g.
>    99 bottles of beer on the wall, 99 bottles of beer
#======================================================================================
# Description:
#   Print out the pseudo lyrics for the song 99 bottles of beer.
#
# Revisions (v1.0):
#   2011.06.26 - 1.0 Created.
#======================================================================================
maxBottles = 99
str1 = '{0} bottle{1} of beer{2}'
str2 = 'on the wall{0}'
bs = 's'

for bottle in range(maxBottles, 0, -1):
  if bottle == 1:
    bs  = '' 

  print str1.format(bottle, bs, ' ') + str2.format(', ') + str1.format(bottle, bs, '.')

> 2. What does range(0, 10, -1) give?  (Try it.)
>    Any idea why?
I got nothing. Probably due to the step being -1, and the stop (10) 
is larger than the start (0). In a for loop it probably exits right
away.

> 3. How was the length of this lesson? Too much, too little or just right?
I like the snippet approach. It works well within a work week.  I wouldn't
mind if it were a little longer.
 
> 4. Write a loop using range() that prints out the first five numbers
>    as words:
>    one
>    two
>    three
>    four
>    five

for i in range(1,6):
  if i == 1:
    print "one"
  elif i == 2:
    print "two"
  elif i == 3:
    print "three"
  elif i == 4:
    print "four"
  elif i == 5:
    print "five"

Peg


More information about the Courses mailing list