条件分岐
概要
条件分岐(if, else elif)
if, else, elif
複数条件は、and or notなどで繋ぐ
i = 15
if i < 10:
print("10未満")
elif i < 20:
print("10以上、20以下")
else:
print("それ以外")
#=> 10以上、20以下
複数条件は、and or notなどで繋ぐ
i, j = 10, 15
if i == 10 and j == 10:
print( "i = 10, j = 10" )
elif i != 10 or j is not 10:
print( "i != 10 || j != 10" )
#=> i != 10 || j != 10
Falseと判定されるもの
Pythonでは、以下の要素がFalseになる。
・None
・False
・0っぽい数字(0, 0.0, 0jなど)
・空っぽいもの(空文字、空リスト、空タプル、空マッピング、etc)
・__bool__か__len__をFalseか0を返すようにしたクラスのインスタンス
・None
print( bool(None) ) #=> False
・False
print( bool(False) ) #=> False
・0っぽい数字(0, 0.0, 0jなど)
# 数字の0はFalse
print( bool(0) )
#=> False
print( bool(0.0) )
#=> False
print( bool(0j) )
#=> False
# 文字列はもちろんTrue
print( bool('0') )
#=> True
・空っぽいもの(空文字、空リスト、空タプル、空マッピング、etc)
print( bool("") )
#=> false
print( bool(()) )
#=> false
print( bool({}) )
#=> false
# 中身が入ればTrueになる
list = []
print( bool( list ) )
#=> False
list.append( "" )
print( bool( list ) )
#=> True
・__bool__か__len__をFalseか0を返すようにしたクラスのインスタンス
class MyClass:
pass
class FalseClass1:
def __bool__(self):
return False
class FalseClass2:
def __len__(self):
return 0
# 普通のクラスのインスタンス
print( bool( MyClass() ) )
#=> True
# __bool__がFalseを返すクラスのインスタンス
print( bool( FalseClass1() ) )
#=> False
# __len__が0を返すクラスのインスタンス
print( bool( FalseClass2() ) )
#=> False
# インスタンスではなくクラスを判定した場合はTrue
print( bool( FalseClass1 ) )
#=> True

