Python : 制御構文

参考書籍 : エキスパートPythonプログラミング, Python実践入門, Python3スキルアップ教科書


演算子
①比較演算子 : ==, >, <, >=, <=, is, is not, in, not in
  is / is not はオブジェクトが同一かを比較
  in / not in はコンテナに含まれているか
②ブール演算子 : and, or, not


・pass : 何もしない

class TestClass(object):  # new style objectから継承
    pass


・if / elif / else

import sys

def version():
    major = sys.version_info.major
    if major == 2:
        return 'Python 2'
    elif major == 3:
        return 'Python 3'
    else:
        return 'Neither'


・for

# for 変数 in イテラブルなオブジェクト:
for i in range(3):
    print(i)

# enumerate()でインデックスを取得できる
chars = 'word'
for count, char in enumerate(chars):
    print(f'{count}番目は{char}')

・for-else
ループの最後に1度だけ実行したい処理をelseに記述
else節はbreakされなかったときに実行される

for number in range(1):
    pass
else:
    print("breakなし")


・while
条件式が真である場合は処理を繰り返す

n = 0
while n < 3:
    print(f"変数nは{n}")
    n += 1

・while-else
for-elseと同じくbreakされなかったときにelse節の処理が行われる


・break/continue
break : ループを抜ける
continue : その行以降の処理をスキップし、次のループ処理を行う


・try/raise/except/else/finally
例外の処理

try:
    raise Exception("ERROR")  # 例外を投げる
except (Exception, ZeroDivisionError) as err:
    print(err)  # 例外が発生したときの処理
else:
    print("例外なし")  # 例外が発生しなかったときの処理
finally:
    print("finally")  # 例外の有無に関わらず実行される処理


・with
クリーンアップが定義済みのオブジェクトの、クリーンアップ処理を自動で呼び出す
__enter__()と__exit__()が定義されたオブジェクトに使用できる

# with withに対応したオブジェクト as 変数:
with open("test.txt", "w") as f:
    f.write("text")