0
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?

【Python】while文の条件はどう書くべきか?

Posted at

Pythonの条件付きループはwhile文を使って書きますが、実は認知負荷の高い書き方をしているのではないか?と思い、まとめてみることにしました。

更新履歴

2025/04/23 : 初版

環境

  • Windows11
  • Python3.12
  • PyCharm Community Edition 2024.2.2

1. while文の2種類の書き方

while文を書く状況としてよくあるのが、「何か処理が完了するまで待機する。一定時間以内に完了しなかった場合、タイムアウトエラーとする」というものだと思います。

これを記述する方法は、次の2つが考えられると思います。

①while直後にTrueを書く
import time

def is_completed() -> bool:
    # 処理が完了していればTrueを、完了していなければFalseを返す
    ...

start_time = time.time()
timeout = 10.0
while True:
    if is_completed():
        break
    if start_time + timeout < time.time():
        raise RuntimeError('timeout')
②while直後に条件を書く
import time

def is_completed() -> bool:
    # 処理が完了していればTrueを、完了していなければFalseを返す
    ...

start_time = time.time()
timeout = 10.0
while time.time() < start_time + timeout:
    if is_completed():
        break
else:
    raise RuntimeError('timeout')

2. 違いについて

この2つを見比べたとき、私には①の方が理解しやすく感じていました。

色々考えて言語化してみると、「if文の条件とwhile文の条件は、性質が真逆だから」という結論に至りました。

具体的に説明します。

ループの終了条件を把握したいとき、①ではbreak, raise, returnに入るif文を探すだけで済みます。

一方②の場合、それに加えてwhile文の条件を否定したものを考える必要があります。

今回はnot (time.time() < start_time + timeout)、つまりstart_time + timeout <= time.time()です。

この「if文だけでなくwhile文も確認する」「if文の条件とwhile文の条件のうち、片方だけを否定する」という作業は、非常に認知負荷が高いと感じています。

3. 結論

上の考察から、while文の条件は書かない(True固定)とした方が理解しやすいコードになるのではと考えました。

実際ここ数年は①の書き方をしていますが、困るような事象は発生していません。

今回の件に関してはwebで調べてみたのですが、言及しているサイトが見つかりませんでした。

もし情報がありましたら連絡をいただけますと幸いです。

また、皆さんの意見もお待ちしています。

0
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
0
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?