見出し画像

【Python】SimplePrograms line 11 (三重引用符: '''と while)

プログラム

11行プログラムです。

REFRAIN = '''
%d bottles of beer on the wall,
%d bottles of beer,
take one down, pass it around,
%d bottles of beer on the wall!
'''
bottles_of_beer = 9
while bottles_of_beer > 1:
    print (REFRAIN % (bottles_of_beer, bottles_of_beer,
        bottles_of_beer - 1))
    bottles_of_beer -= 1

実行結果

9 bottles of beer on the wall,
9 bottles of beer,
take one down, pass it around,
8 bottles of beer on the wall!


8 bottles of beer on the wall,
8 bottles of beer,
take one down, pass it around,
7 bottles of beer on the wall!


7 bottles of beer on the wall,
7 bottles of beer,
take one down, pass it around,
6 bottles of beer on the wall!


6 bottles of beer on the wall,
6 bottles of beer,
take one down, pass it around,
5 bottles of beer on the wall!


5 bottles of beer on the wall,
5 bottles of beer,
take one down, pass it around,
4 bottles of beer on the wall!


4 bottles of beer on the wall,
4 bottles of beer,
take one down, pass it around,
3 bottles of beer on the wall!


3 bottles of beer on the wall,
3 bottles of beer,
take one down, pass it around,
2 bottles of beer on the wall!


2 bottles of beer on the wall,
2 bottles of beer,
take one down, pass it around,
1 bottles of beer on the wall!

解説

11行といっても、6行の文字列と、2行のprint文があるので、実質5行みたいなものである。

1~6行目

REFRAIN = '''
%d bottles of beer on the wall,
%d bottles of beer,
take one down, pass it around,
%d bottles of beer on the wall!
'''

「Triple-quoted strings」三重引用符

Pythonには文字列の表現が三種類あります。

シングルクォート: '"ダブル" クォートを埋め込むことができます'

ダブルクォート: "'シングル' クォートを埋め込むことができます"

三重引用符: '''三つのシングルクォート''', """三つのダブルクォート"""

C言語では、
 シングルクォート:文字
 ダブルクォート:文字列
と、明確な区別がありました。
Pythonではこの区別はないようです。
「文字」は「一文字だけの文字列」でしかありません。

シングルクォートとダブルクォートのあいだに明確な区別はなく、上記のように文字列中にシングルクォートを含むかダブルクォートを含むかというだけで決めることになりそうです。

トリプルクォートは初めて見ました。

Pythonドキュメントによると次のようにあります。

三重引用符文字列は、複数行に分けることができます。

なるほど。
C言語でも文字列に改行コードは入れられませんでした。改行したければエスケープシーケンスで「¥n」と書かなければならなかった。

例えばこんな具合に。

char multi_line[]="test1¥ntest2¥ntest3";

これは、ちょっと、わかりにくい。

Pythonはこれをこんな風に書けるようにしたのですね。

multi_line='''test1
test2
test3'''

7~11行目

bottles_of_beer = 9
while bottles_of_beer > 1:
    print (REFRAIN % (bottles_of_beer, bottles_of_beer,
        bottles_of_beer - 1))
    bottles_of_beer -= 1

「while」文です。

(1)「bottles_of_beer」を9に初期化して
(2)「bottles_of_beer」が1より大きい間は(3)(4)を繰り返す
(3)「REFRAIN」を表示。
 %d にはそれぞれ
  bottles_of_beerと
  bottles_of_beerと
  bottles_of_beer - 1
 を表示する
(4)「bottles_of_beer」を1減算する


ちなみに。

「99 Bottles of Beer」というのは北米の民謡であるらしい。

https://en.m.wikipedia.org/wiki/99_Bottles_of_Beer

遠足などのバスの中で歌われたりするのだとか。

この記事が気に入ったらサポートをしてみませんか?