if/else statementについて

Kazunori Kamiya
Aug 24, 2017 · 3 min read

・Exercise30:ifとelse

ここでは、前回学習したif文に加えてelseというものについて学習していきます。

出力結果について

以下のようになります。

学習ドリル

  1. elsifとelseが、どのような役割を持つか考えてください。
  2. people、cars、trucksの値を変更し、それぞれのif文で何が出力されるか確認してみてください。
  3. cars > people || trucks < carsのような、もう少し複雑なブール論理を作成してみてください。
  4. スクリプトのそれぞれの行の上に、その役割を書いてみてください。

学習ドリルの答え

  1. elsifはその前のif文がfalseで、尚且つelsifの後の条件式がtrueの場合にその処理を実行します。最初のif文の条件式がtrueの場合、その中の処理が実行されてしまうので、elsifの出番はありません。elseは、その前に出てきたifやelsifの条件式がfalseとなって、elseのところまで処理が進んだ場合に実行されます。前のifやelsifの条件式がtrueとなって処理が実行された場合、elseの部分はスキップされます。
  2. peopleを50、carsを20、trucksを10として実行してみました。

3. 以下のようなブール論理の式を加えて実行してみました。

4. 以下のようになります。

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade