異なる状況や条件に対して対応を選択することが可能になるため,if文を使うとプログラムに全く新しい可能性が開かれます。この節では特定の条件に対してどのようにテストし,条件に対応して適切に対応する方法について学びます。
前: 関数入門 | ホーム | 次: whileループと入力
# A list of desserts I like.
desserts = ['ice cream', 'chocolate', 'apple crisp', 'cookies']
favorite_dessert = 'apple crisp'
# Print the desserts out, but let everyone know my favorite dessert.
for dessert in desserts:
if dessert == favorite_dessert:
# This dessert is my favorite, let's let everyone know!
print("%s is my favorite dessert!" % dessert.title())
else:
# I like these desserts, but they are not my favorite.
print("I like %s." % dessert)
if文では複数のテストを必要なだけ使うことができます。その例は後で少し示します。
二つの要素が等値であるのは,それらが同じ値を持つときです。等値性は,数値や文字列,後で習うその他のオブジェクトの間に対してテストできます。結果に驚くこともあるので,以下の例を注意深く見ていくことにしましょう。
Pythonは,他の多くのプログラミング言語同様,二つの等号で等値性をテストします。
注意! 誤って一つの等号を使うと,テストができずに要素にテストしようとしている値を格納してしまいます。
5 == 5
3 == 5
5 == 5.0
'eric' == 'eric'
'Eric' == 'eric'
'Eric'.lower() == 'eric'.lower()
'5' == 5
'5' == str(5)
二つの要素が等しくないのは,それらが同じ値を持たないときです。Pythonでは非等値は感嘆符と等号一つでテストします。
等値をテストしてそれが成り立たないときに非等値とすることがあります。むしろ非等値を直接テストした方が理にかなうこともあります。
3 != 5
5 != 5
'Eric' != 'eric'
5 > 3
5 >= 3
3 >= 3
3 < 5
3 <= 5
3 <= 3
vowels = ['a', 'e', 'i', 'o', 'u']
'a' in vowels
vowels = ['a', 'e', 'i', 'o', 'u']
'b' in vowels
dogs = ['willie', 'hootz', 'peso', 'juno']
if len(dogs) > 3:
print("Wow, we have a lot of dogs here!")
この例では条件が成り立たないときは何も起こりません。
dogs = ['willie', 'hootz']
if len(dogs) > 3:
print("Wow, we have a lot of dogs here!")
エラーは発生しないことに注意しましょう。条件len(dogs) > 3
はFalseに評価され,プログラムはifブロックの後の行に移ります。
多くの場合,テストが取りうる真偽に対してそれぞれ対応する必要があります。テストがTrueに評価されるときあることをして,Falseの時は別のことをします。if-else構造を使うと,次の例のように簡単に実現できます。
dogs = ['willie', 'hootz', 'peso', 'juno']
if len(dogs) > 3:
print("Wow, we have a lot of dogs here!")
else:
print("Okay, this is a reasonable number of dogs.")
結果は変わらないのは,テストがTrueに評価されてif文の下の文だけが実行されているからです。elseの下の文は,テストが不成立の時にのみ実行されます。
dogs = ['willie', 'hootz']
if len(dogs) > 3:
print("Wow, we have a lot of dogs here!")
else:
print("Okay, this is a reasonable number of dogs.")
テストはFalseと評価されましたので,else
の下の文が実行されました。
単にどちらかというだけでなく,一連の条件をテストしたいことも多くあります。これは,if-elif-else文を使えばできます。
テストできる条件の数に制約はありません。常に一つif文から分岐を始めて,elseも一つだけです。しかしelifは必要なだけいくつでも使えます。
dogs = ['willie', 'hootz', 'peso', 'monty', 'juno', 'turkey']
if len(dogs) >= 5:
print("Holy mackerel, we might as well start a dog hostel!")
elif len(dogs) >= 3:
print("Wow, we have a lot of dogs here!")
else:
print("Okay, this is a reasonable number of dogs.")
重要な点は,この例で最初のifだけが評価されていることです。if-elif-else分岐では,テストが一度成立すれば残りの条件は無視されます。
dogs = ['willie', 'hootz', 'peso', 'monty']
if len(dogs) >= 5:
print("Holy mackerel, we might as well start a dog hostel!")
elif len(dogs) >= 3:
print("Wow, we have a lot of dogs here!")
else:
print("Okay, this is a reasonable number of dogs.")
最初のテストが不成立なので,Pythonは2番目のテストを評価しました。このテストが成立したのでlen(dogs) >= 3
に対応する文が実行されます。
dogs = ['willie', 'hootz']
if len(dogs) >= 5:
print("Holy mackerel, we might as well start a dog hostel!")
elif len(dogs) >= 3:
print("Wow, we have a lot of dogs here!")
else:
print("Okay, this is a reasonable number of dogs.")
この例では,最初の二つのテストが不成立なので,else節の文が実行されます。この文は犬が全くいなくても成り立つことに注意してください。
dogs = []
if len(dogs) >= 5:
print("Holy mackerel, we might as well start a dog hostel!")
elif len(dogs) >= 3:
print("Wow, we have a lot of dogs here!")
else:
print("Okay, this is a reasonable number of dogs.")
一連のif文を始めるときには何もする必要はありません。犬がいないときに何もしないようにするには,else
節をもう一つのelif
節に置き換えれば良いでしょう。
dogs = []
if len(dogs) >= 5:
print("Holy mackerel, we might as well start a dog hostel!")
elif len(dogs) >= 3:
print("Wow, we have a lot of dogs here!")
elif len(dogs) >= 1:
print("Okay, this is a reasonable number of dogs.")
この例では,最低1頭の犬がいる場合にだけメッセージを表示しています。もちろん,else
節をさらに追加して犬が全くいない場合に対応することもできます。
dogs = []
if len(dogs) >= 5:
print("Holy mackerel, we might as well start a dog hostel!")
elif len(dogs) >= 3:
print("Wow, we have a lot of dogs here!")
elif len(dogs) >= 1:
print("Okay, this is a reasonable number of dogs.")
else:
print("I wish we had a dog here.")
以上に見られるように,if-elif-else分岐を使うと与えられた場合に対して特定の対応ができます。
crowd_test
のような関数に入れましょう。
(訳注: Two is company, three is a crowd. 二人は友人,三人は他人。ことわざ)else
文をifテストに追加してください。else
文が実行されたら,空席ありというメッセージを印字してください。これまで見てきた例は,一つのテストを通っただけでした。最初のテストが成立すると残りは無視されます。このふるまいは,コードが効率よく走るには良いことです。多くの場合,一つの条件に当てはまればよく,その後の全ての条件は無意味だからです。
他方,一連のテストを走らせて,全てのテストを通したいこともあります。テストのいくつか又は全てを行なって,それぞれのテストに対して対応が必要になることがあります。次の例では,居合せた全ての犬に挨拶します。
dogs = ['willie', 'hootz']
if 'willie' in dogs:
print("Hello, Willie!")
if 'hootz' in dogs:
print("Hello, Hootz!")
if 'peso' in dogs:
print("Hello, Peso!")
if 'monty' in dogs:
print("Hello, Monty!")
if-elif-else分岐を使ったら,最初の犬だけに挨拶するところでした。
dogs = ['willie', 'hootz']
if 'willie' in dogs:
print("Hello, Willie!")
elif 'hootz' in dogs:
print("Hello, Hootz!")
elif 'peso' in dogs:
print("Hello, Peso!")
elif 'monty' in dogs:
print("Hello, Monty!")
もちろん,もっときれいに書くには,リストとforループを使います。次の例は分かりますよね。
dogs_we_know = ['willie', 'hootz', 'peso', 'monty', 'juno', 'turkey']
dogs_present = ['willie', 'hootz']
# Go through all the dogs that are present, and greet the dogs we know.
for dog in dogs_present:
if dog in dogs_we_know:
print("Hello, %s!" % dog.title())
このようなコードを書くことを目指してください。最初は効率の悪いコードでも構いません。一つのプログラム中に同じようなコードを繰り返し書いていることに気づいたら,ループや関数を使って余計なコードを減らせないか検討してみましょう。
全ての値は真または偽に評価することができます。一般的なルールは0ではないか空でない値はTrue
です。もしどちらになるか自信がないときは,Pythonのターミナルを開いて2行書いてみて考えている値がTrue
かFalse
か調べてみましょう。次の例を見て,それを心に留めておいて,興味を持った値をテストしてみましょう。私は通常長いテストを使って毎回何かが印字されるようにしています。
if 0:
print("This evaluates to True.")
else:
print("This evaluates to False.")
if 1:
print("This evaluates to True.")
else:
print("This evaluates to False.")
# Arbitrary non-zero numbers evaluate to True.
if 1253756:
print("This evaluates to True.")
else:
print("This evaluates to False.")
# Negative numbers are not zero, so they evaluate to True.
if -1:
print("This evaluates to True.")
else:
print("This evaluates to False.")
# An empty string evaluates to False.
if '':
print("This evaluates to True.")
else:
print("This evaluates to False.")
# Any other string, including a space, evaluates to True.
if ' ':
print("This evaluates to True.")
else:
print("This evaluates to False.")
# Any other string, including a space, evaluates to True.
if 'hello':
print("This evaluates to True.")
else:
print("This evaluates to False.")
# None is a special object in Python. It evaluates to False.
if None:
print("This evaluates to True.")
else:
print("This evaluates to False.")
前: 関数入門 | ホーム | 次: whileループと入力