1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

while 文っていつ使う?【Day 11】

Last updated at Posted at 2025-12-10

Qiita Advent Calendar 2025 のパイソニスタの一人アドカレ Day11 の記事です。

while 文っていつ使う?

Python の while 文は、条件が True のあいだ繰り返し続けるループです。
「終わりが決まっていない繰り返し」に向いています。

while 文の基本形

while 条件式:
    処理

条件式が True の間ずっと 処理が実行されます。

基本例:カウントアップ

count = 0

while count < 3:
    print(count)
    count += 1

実行結果:

0
1
2

while 文は「条件が変化する」時に使う

例:ユーザー入力が空ではなくなるまで繰り返す

name = ""

while name == "":
    name = input("名前を入力してください: ")

print("ようこそ,", name)

ユーザーが空文字を入れると、何度でも繰り返します。

for と while の違い(ざっくり)

向いている場合
for 回数が決まっている、リストを順に処理する
while 条件が満たされるまで続けたい、終わりが読めない

無限ループに注意

while True: と書くと無限ループになります。

while True:
    print("止まりません")

やりたいときもありますが、初心者は要注意です。

終了条件をきちんと変化させましょう。

break でループを抜けられる

while True:
    word = input("stop と入力すると終了します: ")
    if word == "stop":
        break

まとめ

  • while は「条件が True の間」繰り返す
  • 終了条件が変化するように書くことが重要
  • 回数が決まっているなら for、終わりが見えないなら while
  • 無限ループには注意、必要なら break を使う
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?