Pythonの制御フロー
この記事ではPythonの制御フローについて説明します。
YouTube Video
Pythonにおけるif文
Pythonにおけるif
文は、条件分岐を行うための構文です。これは特定の条件がTrue
(真)である場合に、あるブロックのコードを実行するために使用されます。
基本構文
Pythonのif
文には、基本的に以下のような構造があります。
1x = 10
2
3if x > 5: # Check if the condition(x > 5) is True
4 # If the condition is True, execute this code block
5 print("x is greater than 5")
この例では、変数x
が5より大きい場合に"x is greater than 5"
が出力されます。
else
文
if
文に続けてelse
を使うことで、条件が偽の場合に実行されるコードを指定できます。
1x = 3
2
3if x > 5:
4 print("x is greater than 5")
5else:
6 print("x is less than or equal to 5")
この例の場合、出力は"x is less than or equal to 5"
です。
elif
文
複数の条件をチェックする必要がある場合は、elif
("else if"の略)を使うことができます。
1x = 5
2
3if x > 5:
4 print("x is greater than 5")
5elif x == 5:
6 print("x is equal to 5")
7else:
8 print("x is less than 5")
この例では、"x is equal to 5"
が出力されます。
注意点
if
文やelif
、else
の後にはコロン(:
)が必要です。- 条件が成立した場合に実行されるコードブロックはインデントされます。Pythonではインデントスペースは通常4つですが、一貫性があれば他のスペース数でも問題はありません。
- 条件式にはブール値に評価される任意の式を使用できます。つまり、比較演算子や論理演算子を組み合わせた条件式も使用可能です。
Pythonのif
文を使いこなすことで、プログラムの実行フローを柔軟に制御することができます。
Pythonにおける複数の条件分岐
他の言語でのswitch
文のような機能をPythonで実現するために、いくつかの方法があります。Pythonでは、if-elif-else
文や辞書を使用して、switch
文のような構造を作成することが一般的です。
方法1: if-elif-else
文
最もシンプルな方法は、if-elif-else
文を使って条件分岐を行うことです。
1def switch_example(value):
2 if value == 1:
3 return "Value is one"
4 elif value == 2:
5 return "Value is two"
6 elif value == 3:
7 return "Value is three"
8 else:
9 return "Unknown value"
10
11print(switch_example(1)) # Output: Value is one
12print(switch_example(4)) # Output: Unknown value
方法2: 辞書を使った方法
関数や値を辞書にマッピングすることで、switch
文のような構造を作ることも可能です。これは、特定の値に対して異なる処理を行いたい場合に便利です。
1def case_one():
2 return "Value is one"
3
4def case_two():
5 return "Value is two"
6
7def case_default():
8 return "Unknown value"
9
10def switch_example(value):
11 switch_dict = {
12 1: case_one,
13 2: case_two
14 }
15
16 # Use get() method to retrieve the corresponding function from the dictionary
17 # If the value is not found in the dictionary, use case_default as a fallback
18 return switch_dict.get(value, case_default)()
19
20print(switch_example(1)) # Output: Value is one
21print(switch_example(3)) # Output: Unknown value
方法3: match
文 (Python 3.10以降)
Python 3.10からは、match
文が導入されました。これはパターンマッチングの構文で、switch
文に似た機能を提供します。
1def switch_example(value):
2 match value:
3 case 1:
4 return "Value is one"
5 case 2:
6 return "Value is two"
7 case 3:
8 return "Value is three"
9 case _:
10 return "Unknown value"
11
12print(switch_example(1)) # Output: Value is one
13print(switch_example(4)) # Output: Unknown value
まとめ
if-elif-else
文: 簡単で多くのケースに対応できます。- 辞書: 関数や値のマッピングを使って、効率的に処理を分岐できます。
match
文: Python 3.10以降で使える、より直感的な分岐を行えます。switch
文に最も近いです。
Pythonにおけるfor文
Pythonのfor
文は、反復可能なオブジェクト(リストや文字列、辞書など)の各要素に対して反復処理を行うために使用されます。for
文の基本的な構文は次の通りです。
1# Loop through each item in the iterable
2for variable in iterable:
3 # Execute this block of code for each item in the iterable
4 code_to_execute
以下にいくつかの具体例を示します。
リストを使った例
1fruits = ["apple", "banana", "cherry"]
2for fruit in fruits:
3 print(fruit)
このコードはリストfruits
の各要素に対してprint
関数を呼び出し、それぞれの果物の名前を出力します。
range()を使った例
range()
関数は指定された範囲の整数を生成するので、数値を使った反復処理に便利です。
1for i in range(5):
2 print(i)
range(5)
は0から4までの整数を生成します。この場合、0, 1, 2, 3, 4
が順に出力されます。
辞書を使った例
辞書の場合、デフォルトではキーを反復しますが、キーと値のペアを取得することもできます。
1person = {"name": "Alice", "age": 25}
2for key in person:
3 print(key, person[key])
または、キーと値を同時に取得するにはitems()
メソッドを使用します。
1person = {"name": "Alice", "age": 25}
2for key, value in person.items():
3 print(key, value)
ネストしたfor文
for
文を入れ子にして、複雑な繰り返し処理を行うことも可能です。
1matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
2for row in matrix:
3 for num in row:
4 print(num)
このコードは、リストmatrix
の各行を反復し、各行の数字を順に出力します。
反復をスキップする continue
とループを終了する break
for
文の中でcontinue
を使うと、現在の反復をスキップして次の反復に移ります。また、break
を使うとループを完全に終了します。
1for i in range(10):
2 if i == 5:
3 continue
4 if i == 8:
5 break
6 print(i)
この例では、i
が5の場合はスキップし、8の場合はループを終了します。したがって、出力は0, 1, 2, 3, 4, 6, 7
となります。
Pythonのfor
文は非常に柔軟で、さまざまなシナリオで利用できます。どのような反復処理を行いたいかに応じて、リスト、辞書、文字列、range()
などと組み合わせて使えます。
Pythonにおけるwhile文
Pythonにおけるwhile
文は、条件がTrue
である間、繰り返しブロック内のコードを実行するために使用される制御構造です。while
文の基本的な構文は次のとおりです。
1while condition:
2 # This block of code will be executed repeatedly as long as the condition is true
3 statement1
4 statement2
5 ...
具体例:
次の例では、while
文を使って1から5までの数を出力します。
1i = 1
2while i <= 5:
3 print(i)
4 i += 1
このコードは次のように動作します。
i
を 1 から始めて、i
が 5 以下の間i
を表示し、毎回i
を 1 増やしていきます。
注意点:
while
文では次の点に注意する必要があります。
-
無限ループに注意
while
ループの条件が永遠にTrue
であると、無限ループになります。プログラムが止まらないため、条件が変化する適切な操作をすることが必要です。
-
break
とcontinue
の使用:break
は、ループを途中で終了させたい場合に使用します。continue
は、現在の繰り返しをスキップし、次の繰り返しを開始します。ループ条件が適切でないと無限ループになる可能性があるため注意が必要です。
break
の例:
1i = 1
2while i <= 5:
3 if i == 3:
4 break # Exit the loop when i becomes 3
5 print(i)
6 i += 1
- この場合、
1
と2
が出力された後、i
が3
になった時点でループは終了します。
continue
の例:
1i = 0
2while i < 5:
3 i += 1
4 if i == 3:
5 # Skip the print statement and move to the next loop iteration when i is 3
6 continue
7 print(i)
- この場合、
3
のときだけ出力がスキップされ、結果は1, 2, 4, 5
となります。 i
の値をループの先頭で増やすことで、continue
が実行されても必ずカウンタが進み、無限ループを防いでいます。
YouTubeチャンネルでは、Visual Studio Codeを用いて上記の記事を見ながら確認できます。 ぜひYouTubeチャンネルもご覧ください。