MENÜ

Honlap címe

Előző - #22 Kő, papír, olló | Tartalomjegyzék | Következő - #24 15 percenként

23. GYAKORLAT: 99 ÜVEG SÖR

99 üveg sör a falon,
99 üveg sör,
Vegyél le egyet,
tedd körbe,
98 üveg sör a falon,

A „99 Bottles of Beer on the Wall” egy halmozott dal, amelyet gyakran énekelnek az idő múlatására (és az énekeshez közel állók bosszantására). A hosszú, fárasztó tevékenységek tökéletesek a számítógépek számára. Ebben a gyakorlatban egy programot ír, amely megjeleníti a dal teljes szövegét.

Gyakorlat leírása

Írj egy programot, amely megjeleníti a „99 Bottles of Beer” szövegét. A dal minden szakasza így hangzik:

X üveg sör a falon,

X üveg sör,

Vegyél le egyet,

Hagyd körbe,

 1 üveg sör a falon,

Az X a dalban 99-nél kezdődik, és minden versszaknál eggyel csökken. Ha X egy (és X – 1 nulla), az utolsó sor a „ Nincs több üveg sör a falon! ” Minden strófa után jelenítsen meg egy üres sort, hogy elválassza a következő versszaktól.

Tudni fogja, hogy a program helyes, ha egyezik a https://inventwithpython.com/bottlesofbeerlyrics.txt oldalon található dalszövegekkel . A következőképpen néz ki:

99 üveg sör a falon,

99 üveg sör,

Vegyél le egyet,

Hagyd körbe,

98 üveg sör a falon,

 

98 üveg sör a falon,

98 üveg sör,

Vegyél le egyet,

Hagyd körbe,

97 üveg sör a falon,

…a rövidség kedvéért…

1 üveg sör a falon,

1 üveg sör,

Vegyél le egyet,

Hagyd körbe,

Nincs több üveg sör a falon!

Próbáljon megoldást írni a leírásban szereplő információk alapján. Ha továbbra is problémái vannak ennek a gyakorlatnak a megoldásával, további tippekért olvassa el a Megoldástervezés és a Különleges esetek és Gotchák című részt.

Előfeltétel fogalmak: forciklusok, range() három argumentummal,print()

Megoldás tervezése

Használjon ciklust a 99- től lefelé fortörténő ciklushoz , de nem tartalmazza a . A 3 argumentumú formája ezt megteheti:1range()

for numberOfBottles in tartomány(99, 1, -1)

A numberOfBottlesváltozó az első argumentumnál kezdődik, 99. A második argumentum, az 1 , az az érték, amely numberOfBottles lemegy (de nem tartalmazza). Ez azt jelenti, hogy az utolsó iteráció a numberOfBottles értéket állítja be 2. A harmadik argumentum, -1a lépés argumentum , és az alapértelmezett érték helyett a numberOfBottles értékkel módosítja . Ez azt eredményezi, hogy a for ciklus nem növeli, hanem csökkenti a ciklusváltozót.-11

Például, ha futtatjuk:

for i in range(4, 0, -1):

    print(i)

...a következő kimenetet produkálná:

4

3

2

1

Ha futunk:

for i in range(0, 8, 2):

    print(i)

...a következő kimenetet produkálná:

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).

Special Cases and Gotchas

Python’s print() function accepts multiple arguments to display. These arguments can be strings, integers, Booleans, or values of any other data type. The print() function automatically converts the argument to a string. However, keep in mind that you can only concatenate a string value to another string value. So while these two lines of code are valid:

  • print(numberOfBottles, 'bottles of beer,')
  • print(str(numberOfBottles) + ' bottles of beer,')

This line of code produces a TypeError: unsupported operand type(s) for +: 'int' and 'str' error message because numberOfBottles holds an integer and the + operator cannot concatenate integers to strings.

  • print(numberOfBottles + ' bottles of beer,')

The latter line of code is trying to pass a single argument to print(): the expression numberOfBottles + ' bottles of beer,' evaluates to this single value. This differs from the first two examples where two arguments, separated by a comma, are passed to print(). The difference is a subtle but important. While print() automatically converts arguments to strings, string concatenation doesn’t and requires you to call str() to perform this conversion.

Even the word “convert” is a bit of a misnomer here: function calls return brand new values rather than change an existing value. Calling len('hello') returns the integer value 5. It’s not that the string 'hello' has been changed to the integer 5. Similarly, calling str(42) or int('99') doesn’t change the argument but returns new values.

This is why code such as str(numberOfBottles) doesn’t convert the integer in the numberOfBottles variable to a string. Instead, if you want to change the variable, you need to assign the return value to the variable like:

numberOfBottles = str(numberOfBottles)

Don’t think of this as modifying the value in numberOfBottles, but rather replacing it with the value returned from the str() function call.

Now try to write a solution based on the information in the previous sections. If you still have trouble solving this exercise, read the Solution Template section for additional hints.

Solution Template

Try to first write a solution from scratch. But if you have difficulty, you can use the following partial program as a starting place. Copy the following code from https://invpy.com/bottlesofbeer-template.py and paste it into your code editor. Replace the underscores with code to make a working program:

# Loop from 99 to 2, displaying the lyrics to each stanza.

for numberOfBottles in range(99, 1, ____):

    print(____, 'bottles of beer on the wall,')

    print(____, 'bottles of beer,')

    ____('Take one down,')

    ____('Pass it around,')

 

    # If there is only one, print "bottle" instead of "bottles".

    if (numberOfBottles - 1) == ____:

        ____('1 bottle of beer on the wall,')

    ____:

        print(____ - 1, ' bottles of beer on the wall,')

 

# The last stanza has singular "bottle" and a different final line:

____('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!')

The complete solution for this exercise is given in Appendix A and https://invpy.com/bottlesofbeer.py. You can view each step of this program as it runs under a debugger at https://invpy.com/bottlesofbeer-debug/.

Further Reading

Project #50 in my book, The Big Book of Small Python Projects, also implements this “99 bottles of beer” exercise. You can read it for free online at https://inventwithpython.com/bigbookpython/. Project #51 is a version where the lyrics deteriorate over time with erased letters, swapped letters, and other drunken typos.

Prev - #22 Rock, Paper, Scissors | Table of Contents | Next - #24 Every 15 Minutes

 

Asztali nézet