LoginSignup
3
1

More than 5 years have passed since last update.

[Python] return A [or / and] B

Last updated at Posted at 2015-05-12

return A or B ?

先日、こんなコードを見かけて混乱しました。

def hoge:(self)
    return A or B

return構文内でのorやandは初めて見たので、調べてみます。

なに?

公式ドキュメントからの引用

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

書かないと分からぬ。

or_and_in_return.py
def and_in_return1():
    return 1 == 1 and 1 == 1

def and_in_return2():
    return 1 == 0 and 1 == 1

def and_in_return3():
    return 1 == 1 and 1 == 0

print(and_in_return1()) # True
print(and_in_return2()) # False
print(and_in_return3()) # False

def or_in_return1():
    return 1 == 1 or 1 == 1

def or_in_return2():
    return 1 == 0 or 1 == 0

def or_in_return3():
    return 1 == 1 or 1 == 0

print(or_in_return1()) # True
print(or_in_return2()) # False
print(or_in_return3()) # True

if内で使われている作用と変わりませんでしたね…

参考にさせて頂いたページ

3
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1