Pythonエンジニアへの道

Pythonの基礎知識を綴っています。

条件分岐-if文(2)

if文に「else」をつけると、if文が False  のときの処理が実行される。


コード

score = 30

if score ==100 :                             

    print('congratulations!')                   

    print('よくがんばりました')
                 
else :

    print('がんばりましょう')

 

コンソール

がんばりましょう


if文で条件を複数定義し細分化する場合、「elif」を用いる。

コード

score = 80

if score ==100 :                             

    print('congratulations!')                   
                 
elif score >= 80 :

    print('good!')

elif score >= 60 :

    print('OK')

else :

    print('もう一度チャレンジ!'


コンソール

good!


ここで、「elif」は上部より優先的にならんでいて一度条件に合致し実行されたら下部の条件は無視される。


続いて条件を付け加えてみよう。


①「and」は「かつ」

コード

time = 12

if time > 10 and time < 20 :      ← 省略形として if 10 < time <20 : でもOK!

    print('営業時間内です')

コンソール

営業時間内です




②「or」は「または」

time = 12

if time == 7 or time == 12 or time == 19 :

    print('食事の時間です')

コンソール

食事の時間です



③「not」は条件の否定(条件がFalseならTrue)

time = 4

if not  time >= 5 :

    print('まだ起きる時間ではありません')

コンソール

まだ起きる時間ではありません


これら①〜③を論理演算子と呼ぶ。