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

SJ Straith lupine at sarahj.net
Tue Jun 28 16:38:10 UTC 2011


On 6/24/2011 1:31 PM, Akkana Peck wrote:
> ===================== 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
for i in range(99,0,-1):
     print i, " bottles of beer on the wall\n",i," bottles of beer\n"
> 2. What does range(0, 10, -1) give?  (Try it.)
>     Any idea why?
Within the python shell I get
 >>> range(0,10,-1)
[]
At the DOS prompt I get
    H:\python>range2.py
    H\python>range2.py

At a guess (and that's all it is at this stage) I would say that it 
won't decrement in negative numbers.  ie -1, -2, -3 etc.  Besides, 
putting the range in the order 0, 10 sets the range as 0 to 10 with the 
count down starting at 0.  Since the counter is already at 0 it stops.

> 3. How was the length of this lesson? Too much, too little or just right?
Not to bad. :)
> Problem 4 is optional -- it's a little harder, but give it a try,
> and if you don't get it, take a look at the answers other students
> post. But try it on your own first, if you can.
>
> 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 "Hello, world! i = one"
     elif i == 2:
         print "Hello, world! i = two"
     elif i == 3:
         print "Hello, world! i = three"
     elif i == 4:
         print "Hello, world! i = four"
     elif i == 5:
         print "Hello, world! i = five"
> _______________________________________________
How'd I do, teacher? :)


More information about the Courses mailing list