if/elif/else式
メニューを表示するにはスワイプしてください
最初の if 文の後に追加の条件を確認するには、elif を使用。これにより、複数の条件を順番に評価可能。
if condition_a:
# Do this if `condition_a` is `True`
elif condition_b:
# Do this if `condition_a` is not `True`, but `condition_b` is
else:
# Do this if neither condition is `True`
プログラムで一つだけでなく複数の条件を扱いたい場合がある。if と elif を使うことで、複数の条件を順番に確認可能。最後に else を使うことで、前の条件に当てはまらない場合を処理できる。
123456789101112# Define your age age = 43 # Print a message based on your age if age < 13: print("You are a child.") elif age < 20: print("You are a teenager.") elif age < 65: print("You are an adult.") else: print("You are a senior.")
必要に応じて複数の elif ブロックを積み重ねることが可能。ただし、elif ブロックが多すぎる場合、コードの構造として最も効率的でない場合がある点に注意。
すべて明確でしたか?
フィードバックありがとうございます!
セクション 1. 章 9
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 1. 章 9