Pythonのif文による条件分岐の書き方(if, elif, else)

Modified: | Tags: Python

Pythonのif文(if ... elif ... else ...)による条件分岐について、基本的な書き方と複数条件(and, or)・否定条件(not)などの条件式の指定方法を説明する。

Pythonには条件分岐を一行で記述する三項演算子もある。以下の記事を参照。

Pythonのif文の書き方: if, elif, else

Pythonのif文の基本的な形は以下の通り。

if 条件式 1:
    条件式 1   のときに行う処理
elif 条件式 2 :
    条件式 1  条件式 2   のときに行う処理
elif 条件式 3 :
    条件式 1, 2  条件式 3   のときに行う処理
...
else:
    すべての条件式が  のときに行う処理

ブロックは括弧ではなくインデント(通常はスペース4個)で表現する。

以下、具体例を示す。

ifのみ

ifのみの場合、条件式が真のとき(条件を満たすとき)にブロック内の処理が実行され、偽のとき(条件を満たさないとき)は何もしない。

n = 100

if n > 0:
    print(f'{n} is positive')
# 100 is positive

n = -100

if n > 0:
    print(f'{n} is positive')

if文の条件式は括弧()で囲む必要はない(囲んでもエラーにはならない)。また、例ではブロック内の処理は一行だけだが、もちろん複数行の処理を書いてもよい。

同じif文を繰り返し記載するのを避けるため、ここからの例ではdefで関数を定義して使う。

def if_only(n):
    if n > 0:
        print(f'{n} is positive')

if_only(100)
# 100 is positive

if_only(-100)
source: if_basic.py

文字列への変数の埋め込みにf文字列を使っている。

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
source: if_basic.py

if ... elif ...

elifブロックで、異なる条件に対する処理を追加できる。elifは他のプログラミング言語におけるelse ifelseifに相当し、何個あってもよい。

上から順番に条件をチェックして、最初に条件式が真になったブロックの処理が実行される。すべての条件が偽のときは何もしない。

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)
source: if_basic.py

後述のように、and(かつ)やor(または)を使って、一つの条件式に複数条件の組み合わせを指定することもできる。

if ... elif ... else ...

elifelseは同時に使用できる。ただし、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
source: if_basic.py

if文の条件式

boolを返す式(比較演算子やin演算子など)

これまでの例のように、if文の条件式には、比較演算子などのbool型(True, False)を返す式を指定できる。

Pythonの比較演算子には以下のようなものがある。

演算子 結果
x < y xyより小さければTrue
x <= y xyより小さいか等しければTrue
x > y xyより大きければTrue
x >= y xyより大きいか等しければTrue
x == y xyの値が等しければTrue
x != y xyの値が等しくなければTrue
x is y xyが同一オブジェクトであればTrue
x is not y xyが同一オブジェクトでなければTrue

==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"
source: if_basic.py

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"
source: if_basic.py

bool以外の場合

if文の条件式には、bool型(True, False)でない数値やリストなどの値、およびそれを返す式も指定できる。

if 100:
    print('True')
# True

if [0, 1, 2]:
    print('True')
# True
source: if_basic.py

Pythonでは以下のオブジェクトが偽と判定される。

ゼロを表す数値や空の文字列・リストなどは偽、それ以外はすべて真と判定される。

これを利用すると、リストが空の場合といった条件などがシンプルに書ける。要素数を取得する必要はない。

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
source: if_basic.py

空文字列''以外は真と判定されるため、'False'という文字列も真となるので注意。'True''False'など特定の文字列を1, 0に変換するにはdistutils.utilモジュールのstrtobool()を使う。以下の記事を参照。

if文で複数条件(かつ、または)を指定 :and, or

if文の条件式で複数条件の論理積(かつ)や論理和(または)を指定するには、and, orを使う。

演算子 (if文の条件式での)結果
x and y xyも真であれば真
x or y xyのいずれかが真であれば真
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
source: if_basic.py

複数のandorを使用することもできる。

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
source: if_basic.py

論理演算子の優先順位はnot > and > ornotが最も高い)。また、if文の条件式で使う場合は特に気にする必要はないが、and, orTrueFalseを返すのではなく、左右いずれかの値をそのまま返す。詳細は以下の記事を参照。

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"
source: if_basic.py

なお、例えば==>に対してはnotを付けるのではなく、逆の結果を返す演算子である!=<=を使うほうがシンプルに書ける。

条件式を改行して複数行で記述

複数の条件式をandorで接続して使う場合などで一行が長くなると、条件式を改行して複数行で記述したいときがある。

バックスラッシュ\を使うか、全体を括弧()で囲むことで条件式の途中で改行できる。

書き方が違うだけで、以下の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')
source: if_basic.py
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')
source: if_basic.py
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')
source: if_basic.py

バックスラッシュ\を使えば何度改行してもいい。同様に、括弧()内であれば何度改行してもいい。インデントの制限もない。これはif文に限らずPythonのコードどこでも使えるテクニック。

関連カテゴリー

関連記事