Python Programming Exercises, Gently Explained
71
98 bottles of beer on the wall,
98 bottles of beer,
Take one down,
Pass it around,
97 bottles of beer on the wall,
…cut for brevity…
1 bottle of beer on the wall,
1 bottle of beer,
Take one down,
Pass it around,
No more bottles of beer on the wall!
Try to write a solution based on the information in this description. If you still have trouble
solving this exercise,
read the Solution Design and Special Cases and Gotchas sections for
additional hints.
Prerequisite concepts: for loops, range() with three arguments, print()
Solution Design
Use a for loop to loop from 99 down to, but not including, 1. The 3-argument form of
range()
can do this with:
for numberOfBottles in
range(99, 1, -1)
The numberOfBottles variable starts at
the first argument, 99. The second argument, 1, is the
value that numberOfBottles goes down to (but does not include). This means the last iteration sets
numberOfBottles
to 2.
The third argument, -1, is the
step argument and changes
numberOfBottles
by -1 instead of the default 1. This causes the for loop to decrease the loop
variable rather than increase it.
For example, if we run:
for i in range(4, 0, -1):
print(i)
...it would produce the following output:
4
3
2
1
If we run:
for i in range(0, 8, 2):
print(i)
Python Programming Exercises, Gently Explained
72
...it would produce the following output:
0
2
4
6
The 3-argument form of range() allows you to set more detail than the 1-argument form, but
the 1-argument form is more common because the start and step arguments are often the default 0
and 1, respectively. For example, the code for i in range(10) is the equivalent of for i in
range(0, 10, 1)
.
Dostları ilə paylaş: