LoginSignup
1
1

More than 3 years have passed since last update.

Python制御構文(備忘録)

Last updated at Posted at 2020-11-24

Pythonの制御構文周りの備忘録です。
随時追加・修正を行っていきます。

比較演算子

演算子 説明
A == B AとBが等しい
A != B AとBが等しくない
A < B AがBよりも小さい
A > B AがBよりも大きい
A <= B AがB以下
A >= B AがB以上
A in [LIST] [LIST]の中にAがある
A not in [LIST] [LIST]の中にAがない
A is None AがNoneである
A is not None AがNoneでない
条件A and 条件B 条件Aと条件Bのどちらも満たす
条件A or 条件B 条件Aまたは条件Bのどちらかを満たす

if

num = 5
if num == 0:
    print('数値は0')
elif num < 0:
    print('数値は0より小さい')
else:
    print('数値は0より大きい')

while

limit = input('Enter:') # 入力を受け付ける
count = 0
while True:
    if count >= limit:
        break # countが10以上ならループを抜ける

    if count == 5:
        count += 1
        continue # countが5なら次のループへ

    print(count)
    count += 1
else: # breakされずにループが終了したら実行する
    print('Done')

for

for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
    if i == 5: # iが5なら次のループへ
        continue:

    if i == 8: # iが8ならループを抜ける
        break:

    print(i)
# breakされずにループが終了したら実行する
else:
    print('Done')

# 指定回数処理したいが値を取り出す必要が無い時に_を利用する
for _ in range(10):
    print('hello')

# 2から3つ飛ばしで10を超えるまで処理を行う
for i in range(2, 10, 3):
    print('hello')

# インデックスも取得したい場合
for i, animal in enumerate(['dog', 'cat', 'bird']):
    print(i, animal)

# 複数のリストを同時に展開して取得したい場合
animals = ['dog', 'cat', 'bird']
foods = ['meat', 'fish', 'bean']
for animal, food in zip(animals, foods):
    print(animal, food)

# 辞書のループ処理
data = {'x': 10, 'y': 20}
for k, v in d.items():
    print(k, ':', v)
1
1
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
1
1