本記事について
この記事はプログラミング初学者の私が学んでいく中でわからない単語や概要を分かりやすくまとめたものです。
もし不正などありましたらコメントにてお知らせいただければ幸いです。
制御フロー
条件分岐
- 条件によって分岐のコードを実行する(if-elif-else)
- ブロックは必ずインデントする
- 条件はTrue(真)かFalse(偽)を返す表現を使う
- 条件の後ろにコロン(;)をつける
a = 10
print(a > 0) # True
a = -10
print(a > 0) # False
if a > 0:
print('positive')
else:
print('negative') # negative
*Pythonではインデントで実行ブロックを決定するから、バラバラなインデントは不可
a = 1
if a > 0:
print('成功')
print('失敗') # インデントがばらばらの為エラーがでる
else:
print('マイナスです')
IndentationError: unexpected indent
- 条件によって2つ以上のブロックがある場合は、elifを使う
a = 1
if a == 0:
print('0です')
elif a > 0:
print('1以上です')
else:
print('-1以下です')
- 条件分岐により値を代入することが可能
a = -5
b = 0 if a > 0 else 1
print(b)
- 比較演算子: ==, !=, >, <, >=, <=
- 論理演算し:and, or, not (優先度:not, and, or)
- 要素が入っている: in
a, b, c, i = 10, -5, 20, 2
if (a > 0 or b > 0) and not c == 0 and i in [1,2,3]:
print('利樹です')
- Pythonでは一行のコードが長いとき、分割することができる。
- 継続文字の \ を使う
a, b, c, i = 10, -5, 20, 2
if (a > 0 or b > 0) and \
not c == 0 and \
i in [1,2,3]:
print('利樹です')
参考