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?

More than 1 year has passed since last update.

【Python】While文

Last updated at Posted at 2023-08-05

While文 ループ処理

勉強してたらいろんなことが混ざって分からなくなってきたので、自分なりに書いてみた。


Whileとは?

処理を繰り返し行いたい(ループさせたい)のに使うもの。
または、条件制御ループとも言うらしい。→特定の条件が満たされるあいだ,何かを行う。
真(true)である限り実行を繰り返します。


while文 例文

x = 0              # 初期化  

while x < 5:      # xは5未満
    x += 1         # 1を足していく
    print(x)       

実行結果
1
2
3
4
5

0に1足されてるから、実行結果の最初は1になる
X = -1 に初期値を指定すると、-1+1で0から始まる:point_up:

while + break + if文

break文は、条件が一致したら処理を中断させるもの。
条件が一致したものは表示されず、その前の条件まで表示される。

x = 0

while x < 5:       # xが5 未満の時は、処理を続ける
    x += 1
  
  
    if x == 3:     # xが3 のときに処理を中断する
       break
    print(x)

実行結果
1
2

while + continue + if文

continue文は、中断はせず条件に一致したものをとばすもの。
とばした次の一致していないものを表示させていく。

x = 0

while x < 5:      # xが5 未満の時は、処理を続ける
  x += 1
  
  if x == 3:      # xが3 のときに処理をスキップする
    continue

  print(x)        # 3 のときにはこの下の print は実行されない
実行結果
1
2
4
5

繰り返し
s = 0
n = 1
while n <= 10:            # 10以下のもの
    s += n                # s = 0 + 1
    print(s)
    n += 1                # n = 1 + 1されてwhileのnに代入される(繰り返す)
                          # n += 1が無いと永遠とnは1のままになる
print('end')
実行結果
1
3
6
10
15
21
28
36
45
55
end
0
0
1

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?