4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[python]while文を使ったカウントアッププログラムにおけるbreakとcontinueの書く順番

Posted at

①while文で1から10まで数えるカウントアッププログラムを書き、7に達したらbreakで繰り返しを止める

val = 1
while val < 10:
    if val == 7:
        break
    print(val)
    val += 1

②while文で1から10まで数えるカウントアッププログラムを書き、7に達したら7をスキップして8からまたカウントアップを始める

val = 0
while val < 10:
    val += 1
    if val == 7:
        continue
    print(val)

順番の違い、わかりました!?

この違いをどう受け止めて良いのか分からないけど、
ニュアンス的にはif文の中の処理を中心にコードを考える必要があって、
その違いによって周りの書く順番も変わってくるのかな?と考えています。

break処理は、
「とりあえず俺のことは一度if文ごと忘れてしまって、
その次の処理をやってくれ!繰り返してifの条件に合致してしまった時に気にしてくれ!」
という性質を持っている処理なのだと。

continue処理は、
「if文の前のval + =1 と一体の処理として扱って下さい。val + =1と離れていたら動けないので。」
みたいな感じで、慣れていくしかないのかなと。


僕自身初学者なのでよくわかっていないけど、
プログラミングは数学の方程式にも似ているし英語の文法にも似ているので、
何故こうなのかと細かく理解しようとするよりまずは
「そういうもんなんだ」と受け入れていくしかないと
考えています。

4
4
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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?