[Courses] [python] Lesson 2: Loops, if, and beer
emclaughlin1215 at gmail.com
Sat Jun 25 14:20:25 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
for i in range(99, 0, -1) :
if i < 3 :
bottle = "bottle"
bottle = "bottles"
print i, bottle, "of beer on the wall,"
print i, bottle, "of beer"
print "Take one down, pass it around,"
if i == 1 :
print "No bottles of beer on the wall."
print i-1, bottle, "of beer on the wall.\n"
> 2. What does range(0, 10, -1) give? (Try it.)
> Any idea why?
It gives an empty set (or, when stuck in code, skips the for loop all
together), because 10 is greater than zero, but the counter is getting
-1 added to it (decrementing). And python magically knows that this is
> 3. How was the length of this lesson? Too much, too little or just right?
I think it was too little, but that's because I am an impatient learner.
> 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:
for i in range(1, 6) :
if i == 1 :
elif i == 2 :
elif i == 3 :
elif i == 4 :
elif i == 5 :
print "wtf why isn't the loop working?"
More information about the Courses