条件

条件分岐 の Python

94個の演習

条件分岐について

Pythonでは、if、elif('else and if'の短縮形)、elseの各文を使って、プログラムの実行の流れを制御し、判断を下します。 他の多くのプログラミング言語とは異なり、Python 3.9以前には正式なcase-switch文がなく、代わりに複数のelif文で同様の目的を果たします。

Python 3.10では、pattern matchingと呼ばれるcase-switch文の一種が導入されました。これについては別のコンセプトで扱います。

条件文で使う式は、TrueまたはFalseに評価される必要があります。これは、boolを直接返す場合もあれば、"truthy"または"falsy"を評価する場合もあります。

x = 10
y = 5

# The comparison '>' returns the bool 'True',
# so the statement is printed.
if x > y:
    print("x is greater than y")
...
>>> x is greater than y

ifと組み合わせて使うelseブロックは省略可能で、元のifの条件がFalseと評価されたときに実行されます。

x = 5
y = 10

# The comparison '>' here returns the bool False,
# so the 'else' block is executed instead of the 'if' block.
if x > y:
    print("x is greater than y")
else:
    print("y is greater than x")
...
>>> y is greater than x

elifを使うと、複数の評価や分岐ができます。

x = 5
y = 10
z = 20

# The elif statement allows for the checking of more conditions.
if x > y > z:
    print("x is greater than y and z")
elif y > x > z:
    print("y is greater than x and z")
else:
    print("z is greater than x and y")
...
>>> z is greater than x and y

真偽値の演算と比較は、条件文と組み合わせて、より複雑な判定に使えます。

>>> def classic_fizzbuzz(number):
...     if number % 3 == 0 and number % 5 == 0:
...         say = 'FizzBuzz!'
...     elif number % 5 == 0:
...         say = 'Buzz!'
...     elif number % 3 == 0:
...         say = 'Fizz!'
...     else:
...         say = str(number)
...
...     return say
        
>>> classic_fizzbuzz(15)
'FizzBuzz!'

>>> classic_fizzbuzz(13)
'13'

別の方法として、上の例はreturnsを使ったif文だけで書き直すこともできます。 ただし、このように書き直すと、条件が互いに排他的であることが分かりにくくなり、後々バグやメンテナンスの問題を招くおそれがあります。

>>> def classic_fizzbuzz(number):
...     if number % 3 == 0 and number % 5 == 0:
...         return 'FizzBuzz!'
...     if number % 5 == 0:
...         return 'Buzz!'
...     if number % 3 == 0:
...         return 'Fizz!'
...
...     return str(number)

>>> classic_fizzbuzz(15)
'FizzBuzz!'

>>> classic_fizzbuzz(13)
'13'

条件文は入れ子にすることもできます。

>>> def driving_status(driver_age, test_score):
...     if test_score >= 80:
...         if 18 > driver_age >= 16:
...             status = "Student driver, needs supervision."
...         elif driver_age == 18:
...             status = "Permitted driver, on probation."
...         elif driver_age > 18:
...             status = "Fully licensed driver."
...     else:
...         status = "Unlicensed!"
...
...     return status


>>> driving_status(63, 78)
'Unlicensed!'

>>> driving_status(16, 81)
'Student driver, needs supervision.'

>>> driving_status(23, 80)
'Fully licensed driver.'

条件式、または「三項演算子」

Pythonには?のような専用の三項演算子はありませんが、1行で書けるconditional expressionsを書くことはできます。 これは<value if True> if <conditional test> else <value if False>という形をとります。 この式は読みにくくなることがあるので、1行形式はコードを短くし、読みやすくするのに役立つ場合にだけ使うのがおすすめです。

>>> def just_the_buzz(number):
...     return 'Buzz!' if number % 5 == 0 else str(number)
    
>>> just_the_buzz(15)
'Buzz!'

>>> just_the_buzz(7)
'7'

TruthyとFalsy

Pythonでは、どんなオブジェクトでも真偽値を判定でき、そのため条件文や比較、真偽値の演算に使えます。 このように評価されるオブジェクトは「truthy」または「falsy」とみなされ、boolean contextで使われます。

>>> def truthy_test(thing):
...     if thing:
...         print('This is Truthy.')
...     else:
...         print("Nope. It's Falsy.")


# Empty container objects are considered Falsy.
>>> truthy_test([])
"Nope. It's Falsy."

>>> truthy_test(['bear', 'pig', 'giraffe'])
'This is Truthy.'

# Empty strings are considered Falsy.
>>> truthy_test('')
"Nope. It's Falsy."

>>> truthy_test('yes')
'This is Truthy.'

# 0 is also considered Falsy.
>>> truthy_test(0)
"Nope. It's Falsy."
GitHubで編集 リンクは新しいウィンドウまたはタブで開きます

条件分岐を学習する

練習はロックされています

条件分岐を練習するには、あと4個の演習のロックを解除してください