LoginSignup
0
0

More than 1 year has passed since last update.

Python基本文法2(while文 編)

Last updated at Posted at 2023-02-09

概要

Python初心者です。自分の備忘録用2です。
前回のPython基本文法1(リスト、辞書、for文 編)の続きです。
どなたかの助けになれば幸いです。

勉強したサイト

Progate

while文

x = 1
while x <= 100:
 print(x)
 x += 1
# ↑Xがtrue(今回はXが100より多くなるまで)の間、下2行の処理を繰り返します。
1
2
3
...
100
注意!
x = 1
while x <= 100:
 print(x)

# ↑Xが更新されないように書くと...
1
1
1
1
1
1
.
.
.

と、永遠に処理を繰り返します。これは異常な負荷がかかるので、確実に条件がfalseになるようにしましょう!
また、

x = 1
while x <= 100:
 print(x)
X += 1
# ↑printの下のx += 1がprintのbインデントに含まれていないと...
1
1
1
1
1
1
.
.
.

これも永遠に処理を繰り返します!注意!

break文

繰り返し処理の際、途中で処理を終わらせるためのコマンド

numbers = [1,2,3,4,5,6,7,8,9]
for number in numbers:
    print(number)
    if number == 3:
        break
# ↑もしnumberが3の時、処理を強制終了する
ターミナルの例.
1
2
3

continue文

ターミナル.
numbers = [1,2,3,4,5,6,7,8,9]
for number in numbers:
    if number % 2 == 1: ←取り出したnumberが2で割り切れる(偶数)の場合
        continue
    print(number)
ターミナルの例.
1
3
5
7
9
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