0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【6】【python】基本の基本:条件分岐を使おう。

Last updated at Posted at 2025-11-16

下記のコード

score = 70
print(score > 60)
print(score > 80)

実行すると結果は

True
False

となります。

私は「何でエラーにならないで真偽値で返してくるんだろう?」と疑問に思いました。
答えは「エラーにならないのは、Python が “比較すると必ず真偽値(bool)を返す” と決めているから」です。
そういうのだと思った方が早そうですね。

では比較すると真偽値を返すのであれば
真偽値によって処理を変えることができたら便利ですよね。
そこでif文の登場です。

以下のコード

score = 70
if score >= 80:
    print("やったね")
    print("この調子で頑張ろう")

この結果は何も出ません。

なぜかというと、条件を満たしていないから。
かつ条件を満たさなかった場合の処理を書いてないから、です。

では

score = 80
if score >= 80:
    print("やったね")
    print("この調子で頑張ろう")

として条件を満たしてあげましょう。
結果

やったね
この調子で頑張ろう

となりました。

さらに
「もしもXXだったOOして、そうでなかったら■ ■にするという処理を行いましょう。

score = 70
if score >= 80:
    print("やったね")
    print("この調子で頑張ろう")

else:
    print("残念")

結果は

残念

となりました。満たしてない条件の場合の処理をelseに書いたからですね。

ではinputを使って条件分離するコードを書いてみましょう。

age = int(input("あなたは何歳ですか?"))
if age < 20:
    print("お酒は二十歳を過ぎてから")
else:
    print("飲み過ぎにご注意ください")

18と入力した場合

あなたは何歳ですか?18
お酒は二十歳を過ぎてから

25と入力した場合

あなたは何歳ですか?25
飲み過ぎにご注意ください

というわけで入力に対して分岐処理ができましたね。

★ポイント
pythonは比較が行われた場合「真偽値」を返す。
※これは繰り返し処理のときにも重要な考え方になります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?