Pythonの初心者レッスンーーPython条件制御(if-else)
シーリズの目次
Pythonの初心者レッスンをここにまとめています。
Pythonの条件制御は、プログラムの実行フローを制御するために使用されます。これは主に、if文、elif文、およびelse文を使用して行われます。
条件制御の実行手順は次の図で簡単にわかります。
コード実行手順です:
if
、elif
、else
文
if
文は、条件が真(True)の場合に特定のコードブロックを実行します。
elif
文(else ifの略)は、最初のif条件が偽(False)で、他の条件をチェックしたい場合に使用します。
else
文は、すべてのifおよびelif条件が偽の場合に実行されるコードブロックを指定します。
一般的な形式は以下の通りです。
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3
- "condition 1"がTrueの場合は、"statement block 1"ブロック文を実行します。
- "condition 1"がFalseの場合は"condition 2"と判断されます
- "condition 2"がTrueの場合は、"statement block 2"ブロック文を実行します。
- "condition 2"がFalseの場合、"statement block 3"ブロック文が実行されます。
注意:
- それぞれの条件の後にコロン
:
を使い、条件を満たすと実行される文のブロックが続いていることを示します。 - インデントを使って文のブロックを分割し、同じインデント数の文を一つのブロックにします。
条件制御の例
age = 10
if age >= 18:
print("成人です。")
elif age >= 13:
print("ティーンエイジャーです。")
else:
print("子供です。")
演算子
以下は、Pythonのif文でよく使われる操作(比較)演算子をまとめたテーブルです。
操作演算符 | 説明 | 使用例 | 結果 |
---|---|---|---|
== |
等しい | x == y |
True if x is equal to y
|
!= |
等しくない | x != y |
True if x is not equal to y
|
> |
より大きい | x > y |
True if x is greater than y
|
< |
より小さい | x < y |
True if x is less than y
|
>= |
以上 | x >= y |
True if x is greater than or equal to y
|
<= |
以下 | x <= y |
True if x is less than or equal to y
|
and |
両方が真(True) | x > 0 and y > 0 |
True if both x > 0 and y > 0 are True |
or |
どちらかが真(True) | x > 0 or y > 0 |
True if either x > 0 or y > 0 is True |
not |
否定 | not x |
True if x is False |
in |
メンバーシップ | x in y |
True if x is in y
|
not in |
メンバーシップの否定 | x not in y |
True if x is not in y
|
is |
オブジェクト同一性 | x is y |
True if x and y are the same object |
is not |
オブジェクト同一性の否定 | x is not y |
True if x and y are not the same object |
条件制御のネスト
条件文をネストして使用することもできます。
age = 16
gender = "female"
if age >= 18:
if gender == "male":
print("成人男性です。")
else:
print("成人女性です。")
else:
if gender == "male":
print("未成年男性です。")
else:
print("未成年女性です。")
このコードは、年齢と性別に基づいて異なるメッセージを表示します。
複数条件の使用
複数の条件を組み合わせて使用することもできます。論理演算子and
およびor
を使用します。
age = 22
income = 40000
if age > 18 and income > 30000:
print("融資が可能です。")
else:
print("融資ができません。")
このコードは、年齢が18歳以上で収入が30000以上の場合に「融資が可能です」と表示し、それ以外の場合は「融資ができません」と表示します。
match...case
Python 3.10 で導入された match...case 構文は、パターンマッチングを提供します。これは、複数の条件を効率的に処理するための新しい構文であり、特に複雑な条件分岐を簡潔に書くために便利です。match...case 構文は、スイッチ文や条件分岐を含む多くのケースで役立ちます。
基本構文
match 式:
case パターン1:
実行するコード1
case パターン2:
実行するコード2
case パターン3:
実行するコード3
case _:
その他のすべてのケースに対するコード
例: シンプルなパターンマッチング
def http_status(status):
match status:
case 200:
return "OK"
case 404:
return "Not Found"
case 500:
return "Internal Server Error"
case _:
return "Unknown Status"
print(http_status(200)) # 出力: OK
print(http_status(404)) # 出力: Not Found
print(http_status(123)) # 出力: Unknown Status
match...case
構文は、複雑な条件分岐をシンプルに表現するための強力なツールです。Python 3.10 以降で利用可能なので、バージョンに注意してください。これを使うことで、コードの可読性が向上し、複数の条件に基づく処理を簡潔に書くことができます。
Discussion