Python: while 文 (繰り返し)

Python 独習メモ


while 条件式

    条件好きが成立したときの処理


count = 0

counts = []

while count <= 5:

    counts.append(count)

    print(counts)

    count = count + 1

実行結果

[0]

[0, 1]

[0, 1, 2]

[0, 1, 2, 3]

[0, 1, 2, 3, 4]

[0, 1, 2, 3, 4, 5]


回数ではなく状態(True/False)で繰り返す。

is_hunger = True
count = 0
while is_hunger == True:
    count += 1
    print('{}杯目のラーメンを召し上がれ^^'.format(count))
    key = input('お腹いっぱい?(y/n)>>')
    if key == 'y':
        is_hunger = False
print('まいどあり')
実行結果
1杯目のラーメンを召し上がれ^^
お腹いっぱい?(y/n)>>n
2杯目のラーメンを召し上がれ^^
お腹いっぱい?(y/n)>>y
まいどあり

ある事柄や状態を二者択一で表すには、bool 型を利用する。フラグとなる変数名は一般的に "is_xxx" とする。


繰り返しでリストを作成。
count = 0
cat_num = int(input('ネコは何匹ですか?>>'))
weight_list = list()  # list 関数(コレクション変換)を使って空のリストを作る
while count < cat_num:
    count += 1
    weight = float(input('{}匹目の体重を入力>>'.format(count)))
    weight_list.append(weight)       # リストに要素を追加している
print(weight_list)
total = sum(weight_list)
print('平均体重は{:.1f}kgです'.format(total / cat_num))       # ':.1f' は少数以下の桁を指定
実行結果
ネコは何匹ですか?>>3
1匹目の体重を入力>>4.2
2匹目の体重を入力>>4.5
3匹目の体重を入力>>5.1
[4.2, 4.5, 5.1]
平均体重は4.6kgです







続く........


このブログの人気の投稿

日本のオーディオメーカー一覧

「ミュージック」アプリでアルバムアートが削除できない

メディアサーバーの Plex, Emby, Jellyfin を試す

増え続ける iTunes のコンピレーションを減らす(Windows)

電力会社と音質