Pythonのif文による条件分岐の書き方(if, elif, else)
Pythonのif文による条件分岐(if ... elif ... else ...
)について、基本的な書き方や複数条件・否定条件を含む条件式の指定方法などを説明する。
Pythonには条件分岐を一行で記述する三項演算子もある。以下の記事を参照。
Pythonのif文の書き方: if, elif, else
Pythonのif文の基本的な形は以下の通り。
if 条件式 1:
条件式 1 が 真 のときに行う処理
elif 条件式 2 :
条件式 1 が 偽、条件式 2 が 真 のときに行う処理
elif 条件式 3 :
条件式 1, 2 が 偽、条件式 3 が 真 のときに行う処理
...
else:
すべての条件式が 偽 のときに行う処理
ブロックは括弧ではなくインデント(通常はスペース4個)で表現する。
以下、具体例を示す。def文で関数を定義し、文字列への変数の埋め込みにf文字列を使う。
ifのみ
if
のみの場合、条件式が真のとき(条件を満たすとき)に指定した処理が実行され、偽のとき(条件を満たさないとき)は何もしない。
def if_only(n):
if n > 0:
print(f'{n} is positive')
if_only(100)
# 100 is positive
if_only(-100)
if文の条件式は括弧()
で囲む必要はない(囲んでもエラーにはならない)。また、例ではブロック内の処理は一行だけだが、複数行に渡る処理を書いてもよい。
if ... else ...
else
ブロックで、条件式が偽のとき(条件を満たさないとき)の処理を追加できる。
def if_else(n):
if n > 0:
print(f'{n} is positive')
else:
print(f'{n} is negative or zero')
if_else(100)
# 100 is positive
if_else(-100)
# -100 is negative or zero
if ... elif ...
elif
ブロックで、異なる条件に対する処理を追加できる。elif
は他のプログラミング言語におけるelse if
やelseif
に相当し、何個あってもよい。
上から順番に条件をチェックして、真になったブロックの処理が実行される。すべての条件が偽のときは何もしない。
def if_elif(n):
if n > 0:
print(f'{n} is positive')
elif n == 0:
print(f'{n} is zero')
elif n == -1:
print(f'{n} is minus one')
if_elif(100)
# 100 is positive
if_elif(0)
# 0 is zero
if_elif(-1)
# -1 is minus one
if_elif(-100)
後述のように、and
(かつ)やor
(または)を使って、一つの条件式に複数条件の組み合わせを指定することもできる。
if ... elif ... else ...
elif
とelse
は同時に使用できる。ただし、else
は必ず最後でなければならない。すべての条件が偽のときにelse
ブロックの処理が実行される。
def if_elif_else(n):
if n > 0:
print(f'{n} is positive')
elif n == 0:
print(f'{n} is zero')
else:
print(f'{n} is negative')
if_elif_else(100)
# 100 is positive
if_elif_else(0)
# 0 is zero
if_elif_else(-100)
# -100 is negative
if文の条件式
boolを返す式(比較演算子やin演算子など)
これまでの例のように、if文の条件式には、比較演算子などのbool
型(True
, False
)を返す式を指定できる。
Pythonの比較演算子には以下のようなものがある。
演算子 | 結果 |
---|---|
x < y |
x がy より小さければTrue |
x <= y |
x がy より小さいか等しければTrue |
x > y |
x がy より大きければTrue |
x >= y |
x がy より大きいか等しければTrue |
x == y |
x とy の値が等しければTrue |
x != y |
x とy の値が等しくなければTrue |
x is y |
x とy が同一オブジェクトであればTrue |
x is not y |
x とy が同一オブジェクトでなければTrue |
==
とis
の違いについては以下の記事を参照。
- 関連記事: Pythonの==演算子とis演算子の違い
Pythonでは複数の比較演算子を連結してa < x < b
のような書き方もできる。
リストや文字列に特定の要素(文字)が含まれているかを条件にすることも可能。in
(含む)、not in
(含まない)を使う。
def if_in(s):
if 'a' in s:
print(f'"a" is in "{s}"')
else:
print(f'"a" is not in "{s}"')
if_in('apple')
# "a" is in "apple"
if_in('cherry')
# "a" is not in "cherry"
bool
を返すメソッドや関数を条件式として指定することもできる。例えば、startswith()
は前方一致を判定する文字列のメソッド。
def if_startswith(s):
if s.startswith('a'):
print(f'"{s}" starts with "a"')
else:
print(f'"{s}" does not start with "a"')
if_startswith("apple")
# "apple" starts with "a"
if_startswith("banana")
# "banana" does not start with "a"
bool以外の場合
if文の条件式には、bool型(True
, False
)でない数値やリストなどの値(およびそれを返す式)も指定できる。
if 100:
print('True')
# True
if [0, 1, 2]:
print('True')
# True
Pythonでは以下のオブジェクトが偽と判定される。
- 偽であると定義されている定数:
None
とFalse
.- 数値型におけるゼロ:
0
,0.0
,0j
,Decimal(0)
,Fraction(0, 1)
- 空のシーケンスまたはコレクション:
''
,()
,[]
,{}
,set()
,range(0)
組み込み型 - 真理値判定 — Python 3.12.0 ドキュメント
ゼロを表す数値や、空の文字列・リストなどは偽と判定され、それ以外はすべて真と判定される。
これを利用すると、リストが空の場合といった条件などがシンプルに書ける。要素数を取得する必要はない。
def if_is_empty(l):
if l:
print(f'{l} is not empty')
else:
print(f'{l} is empty')
if_is_empty([0, 1, 2])
# [0, 1, 2] is not empty
if_is_empty([])
# [] is empty
空文字列''
以外は真と判定されるため、'False'
という文字列も真となるので注意。'True'
や'False'
など特定の文字列を1
, 0
に変換するにはdistutils.utilモジュールのstrtobool()
を使う。以下の記事を参照。
if文で複数条件(かつ、または)を指定 :and, or
if文の条件式で複数条件の論理積(かつ)や論理和(または)を指定するには、and
, or
を使う。
演算子 | (if文の条件式での)結果 |
---|---|
x and y |
x もy も真であれば真 |
x or y |
x とy のいずれかが真であれば真 |
def if_and(n):
if n > 0 and n % 2 == 0:
print(f'{n} is positive-even')
else:
print(f'{n} is not positive-even')
if_and(10)
# 10 is positive-even
if_and(5)
# 5 is not positive-even
if_and(-10)
# -10 is not positive-even
複数のand
やor
を使用することもできる。
def if_and_or(n):
if n > 0 and n % 2 == 0 or n == 0:
print(f'{n} is positive-even or zero')
else:
print(f'{n} is not positive-even or zero')
if_and_or(10)
# 10 is positive-even or zero
if_and_or(5)
# 5 is not positive-even or zero
if_and_or(0)
# 0 is positive-even or zero
論理演算子の優先順位はnot > and > or
(not
が最も高い)。また、if文の条件式で使う場合は特に気にする必要はないが、and
, or
はTrue
かFalse
を返すのではなく、左右いずれかの値をそのまま返す。詳細は以下の記事を参照。
if文で否定(でない)を指定: not
if文の条件式で否定(でない)を指定するには、not
を使う。
def if_not(s):
if not s.startswith('a'):
print(f'"{s}" does not start with "a"')
else:
print(f'"{s}" starts with "a"')
if_not("apple")
# "apple" starts with "a"
if_not("banana")
# "banana" does not start with "a"
なお、例えば==
や>
に対してはnot
を付けるのではなく、逆の結果を返す演算子である!=
や<=
を使うほうがシンプルに書ける。
条件式を改行して複数行で記述
複数の条件式をand
やor
で接続して使う場合などで一行が長くなると、条件式を改行して複数行で記述したいときがある。
バックスラッシュ\
を使うか、全体を括弧()
で囲むことで条件式の途中で改行できる。
書き方が違うだけで、以下の3つの関数はすべて等価。
def if_no_newline():
if too_long_name_function_1() and too_long_name_function_2() and too_long_name_function_3():
print('True')
else:
print('False')
def if_backslash():
if too_long_name_function_1() \
and too_long_name_function_2() \
and too_long_name_function_3():
print('True')
else:
print('False')
def if_parentheses():
if (
too_long_name_function_1()
and too_long_name_function_2()
and too_long_name_function_3()
):
print('True')
else:
print('False')
バックスラッシュ\
を使えば何度改行してもいい。同様に、括弧()
内であれば何度改行してもいい。インデントの制限もない。これはif文に限らずPythonのコードどこでも使えるテクニック。
- 関連記事: Pythonで長い文字列を複数行に分けて書く