エディタの横のカンペ集⑤ 分岐処理

分岐処理

Pythonの分岐処理(条件分岐)は、if 文を使用して特定の条件に応じた処理を実行します。条件を適切に設定することで、柔軟なプログラムの構築が可能になります。


1. if 文の基本構文

Pythonのif 文は、条件が True の場合にコードを実行する。

x = 10
if x > 5:
print("x is greater than 5") # 実行される

条件が False の場合は何も実行されない。

x = 3
if x > 5:
    print("x is greater than 5")  # 実行されない

2. elif と else の使い方

複数の条件を判定する場合は elif(else if)を使用し、どの条件にも当てはまらない場合は else を使う。

x = 10
if x > 10:
print("x is greater than 10")
elif x == 10:
print("x is equal to 10") # 実行される
else:
print("x is less than 10")

3. 条件式の省略記法

三項演算子を使用すると、簡潔に条件分岐が記述できる。

x = 5
y = "Positive" if x > 0 else "Non-positive"
print(y)

# 実行内容>>Positive

4. in を使った判定

リストや文字列内に特定の値が含まれているかを判定できる。

fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("Banana is in the list")

# 実行内容>>Banana is in the list

5. and・or・not を使った複数条件

複数の条件を組み合わせて判定できる。

x = 10
y = 5
if x > 5 and y < 10:
print("Both conditions are True")

# 実行内容>>Both conditions are True

or を使うと、いずれかの条件が True なら実行される。

x = 10
y = 5

if x > 10 or y < 10:
print("At least one condition is True")

# 実行内容>>At least one condition is True

not は条件を反転する。

x = 10
y = 5

if not x < 5:
print("x is not less than 5")

# 実行内容>>x is not less than 5

6. match-case(Python 3.10以降)

match-case を使うと、複数の条件をスイッチ文のように記述できる。

value = "apple"
match value:
case "apple":
print("It's an apple")
case "banana":
print("It's a banana")
case _:
print("Unknown fruit")
#実行内容>>It's an apple

コメント

タイトルとURLをコピーしました