Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ 条件の組み合わせ | 条件文
Python入門
セクション 3.  2
single

single

book条件の組み合わせ

メニューを表示するにはスワイプしてください

ブール値の理解を基礎として、ここではPythonで複数の条件を組み合わせる方法について学びます。このスキルにより、プログラムは複数の基準を同時に確認し、より細かな判断が可能になります。 アレックスが複数の条件を組み合わせて、食料品店の運営でより良い判断を下す様子を見てみましょう:

複合条件の理解

Pythonでは、andornotなどの論理演算子を使って条件を組み合わせることができます。これらの演算子により、複数のブール式を評価する複合条件を作成できます。

  • and: 両方の条件がTrueの場合にTrueを返す;
  • or: 少なくとも1つの条件がTrueの場合にTrueを返す;
  • not: 条件がTrueの場合にFalseを返す(逆も同様)。

応用例

and演算子を使って、商品が生鮮食品でかつ在庫が多いかどうかを確認するために条件を組み合わせてみましょう:

12345678910111213
# Define the perishable and stock status conditions is_perishable = True item_quantity = 110 perishable_highStockRisk = 100 # Using the (and) operator to combine two conditions # The first condition (`is_perishable`) checks if the item is perishable # The second condition (`item_quantity >= perishable_highStockRisk`) checks if the item is high in stock # The `consider_discount` variable will become `True` only if both conditions are `True` consider_discount = is_perishable and (item_quantity >= perishable_highStockRisk) # Print the result print("Is the item perishable and high in stock?", consider_discount)
copy

次に、or 演算子を使用して、商品が季節商品 または 祝日商品かどうかを条件を組み合わせて確認します。

12345678910
# Define the seasonal and holiday status conditions seasonal_item = False holiday_item = True # Combine the conditions to check if the item is seasonal or discounted # (`temporary_stock`) will become `True` if either condition `seasonal_item` OR `holiday_item` is `True` temporary_stock = seasonal_item or holiday_item # Print the result print("Is this a seasonal or holiday item?", temporary_stock)
copy

最後に、not 演算子を使って、アイテムが再価格設定を必要としないかどうかを条件を組み合わせて確認:

12345678
# Define the item status condition is_perishable = True # Use the `not` operator to check if the item is NOT perishable long_shelf_life = not is_perishable # Print the result print("Does the item need to be sold quickly?", long_shelf_life)
copy
タスク

スワイプしてコーディングを開始

商品の割引または在庫が少ないかどうかを評価し、プロモーション対象かを判断します。

  • 論理演算子を用いて、商品が割引されているまたは在庫が少ない場合にmovingProductとなるブール型変数Trueを定義します。
  • 商品が割引されておらず、十分な在庫がある(つまり在庫が少なくない)場合にpromotionとなるブール型変数Trueを作成します。
  • メッセージを出力します:Is the item eligible for promotion? <promotion>

出力要件

商品がプロモーション対象かどうかを出力してください:

Is the item eligible for promotion? <promotion>

解答

Switch to desktop実践的な練習のためにデスクトップに切り替える下記のオプションのいずれかを利用して、現在の場所から続行する
すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 3.  2
single

single

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

some-alt