例えば score が 60 以上なら Congratulation!,60 未満なら Sorry! と表示するプログラムは次のようになります.ここで,if
や else
の行の最後に :
が必要であることに注意する必要があります.また,if
の中身がどこまでであるかは,インデント(字下げ)で指定します.つまり,print
の前に半角スペースを4個入力する(Jupyter Notebook の場合は Tab キーでも良いでしょう.Visual Studio Code では設定項目の「Editor: Insert Spaces」にチェックを入れて,「Editor: Tab Size」を「4」に設定すれば Tab キーだけで4つのスペースが入力されます.Atom の場合は「設定」→「エディタ設定」→「ソフトタブ」にチェックを入れ,「タブ幅」を「4」にするとよい).インデントが重要な意味を持っているのは Python の特徴であり,多くの他の言語とは異なる部分です.なお,Python コードのスタイルガイド (PEP 8) はここを参照してください.
- score = 70
- if score >= 60:
- print("Congratulation!")
- else:
- print("Sorry!")
Congratulation!
次の 2 種類のコードでインデントがどのように影響するかを考えよう.
- score = 70
- if score >= 60:
- print("Congratulation!")
- else:
- print("Sorry!")
- print('score = ', score) # if, else の外側なので,常に実行される
Congratulation! score = 70
- score = 70
- if score >= 60:
- print("Congratulation!")
- else:
- print("Sorry!")
- print('score = ', score) # else の中なので,60 以上なら実行されない
Congratulation!
3通り以上に場合分けをしたい場合は,if, elif, else を使えば良いでしょう.
- score = 83
- if score >= 90:
- print("S")
- elif score >= 80:
- print("A")
- elif score >=70:
- print("B")
- elif score >=60:
- print("C")
- else:
- print("D")
A
Python では次の比較演算子が利用できます.
演算子 | 意味 |
---|---|
== | 等しい |
!= | 等しくない |
< | より小さい |
<= | 以下 |
> | より大きい |
>= | 以上 |
in | 要素にある |
なお,「等しい」は ==
のように = を2つ並べて書くことに注意する必要があります.
- signal = 'green'
- if signal == 'green':
- print("Go")
- else:
- print("Stop")
Go
複数の条件で「かつ」や「または」を表現したければ,and
,or
,not
を使います.例えば,数学と科学の得点が両方とも 60 以上の時だけ Congratulation! と表示します.
- mathematics = 70
- science = 70
- if mathematics >= 60 and science >= 60:
- print("Congratulation!")
Congratulation!
複数の条件を「または」で表現する状況を想定してみよう.例えば,曜日が「Monday」「Tuesday」「Wednesday」「Thursday」「Friday」なら授業日で,「Saturday」「Sunday」ならば授業のない日,それ以外なら入力ミスと判定したい状況を考えます.このとき,or
を使って記述すると次のようになります.
- day = 'Tuesday'
-
- if day == 'Monday' or day == 'Tuesday' or day == 'Wednesday' or day == 'Thursday' or day == 'Friday':
- print('授業日です')
- elif day == 'Saturday' or day == 'Sunday':
- print('授業のない日です')
- else:
- print('入力ミス?')
授業日です
しかし,or
を使わずに,変数 in リスト
のように記述して,変数がリストに含まれるかどうかを判定することで,よりスッキリと記述できるようになります.
- day = 'Tuesday'
-
- if day in ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']:
- print('授業日です')
- elif day in ['Saturday', 'Sunday']:
- print('授業のない日です')
- else:
- print('入力ミス?')
授業日です