[Courses] [python] Lesson 2: Loops, if, and beer
Kathryn Marks
kathryn.linux at gmail.com
Sat Jun 25 11:28:18 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
>
#!/usr/bin/python
# 99bottlesofbeer.py
# Kathryn Marks
# kathryn.python at gmail.com
# Created June 25, 2011
# Last modified June 25, 2011
# A short program to print out the lyrics of that favorite bus song.
# Linux Chix python course lesson 2, homework problem 1
# Demonstrates loops, if, else, and elif
# With a unique Korean reference at the end
for i in range(99, -1, -1):
if i==1:
print i,"bottle of beer on the wall,",i,"bottle of beer."
print "Take one down and pass it around,"
print i-1,"bottles of beer on the wall."
elif i==0:
print "No more bottles of beer on the wall. How about some soju?"
else:
print i,"bottles of beer on the wall,",i,"bottles of beer."
print "Take one down and pass it around,"
print i-1,"bottles of beer on the wall."
#EOF
>
> 2. What does range(0, 10, -1) give? (Try it.)
> Any idea why?
>
You get [ ]
You're telling python to count from 0 to 10 by subtracting one. That's
mathematically impossible. You have to add 1 to get from 0 to 10.
> 3. How was the length of this lesson? Too much, too little or just right?
>
Pretty much right on the money.
> 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
>
#!/usr/bin/python
# counting.py
# Kathryn Marks
# kathryn.python at gmail.com
# Created June 25, 2011
# Last modified June 25, 2011
# A short program to print out the words for the number 1-5.
# Linux Chix python course lesson 2, homework problem 4
# Demonstrates loops, if, else, and elif
for i in range(1, 6, 1):
if i==1:
print "one"
elif i==2:
print "two"
elif i==3:
print "three"
elif i==4:
print "four"
else:
print "five"
#EOF
> _______________________________________________
> Courses mailing list
> Courses at linuxchix.org
> http://mailman.linuxchix.org/mailman/listinfo/courses
>
--
~Kathryn
More information about the Courses
mailing list