nikuyoshiのブログ

記事の内容については個人の見解であり、所属企業の意見を代表するものではありません

みんなのPython Chapter03(条件分岐とループ)

if文の簡単な例

>>> if year == 1868:
...     print u"明治元年"
... 
明治元年

else文の簡単な例

>>> year = 1900
>>> if year == 1868:
...     print u"明治元年"
... else:
...     print u"明治", year-1867, u""
... 
明治 33 年

elif文による書き換え

>>> if year == 1868:
...     print u"明治元年"
... elif 1869 <= year <= 1911:
...     print u"明治", year-1867, u""
... elif year == 1912:
...     print u"大正元年"
... 
大正元年

比較演算子の例

>>> a = 1
>>> a == 1
True
>>> a == 2
False
>>> a
1

18歳以下、65歳以上、ただし0歳を除く(論理演算子の優先順位)

  • 正常に動作しない例
>>> if age <= 18 or age >= 65 and age != 0:
...     print "True"
... else:
...     print "False"
... 
True
  • ()で優先順位を指定
>>> age = 0
>>> if (age <= 18 or age >= 65) and age != 0:
...     print "True"
... else:
...     print "False"
... 
False

違う型の比較

>>> s = "this is ASCII string"
>>> s == "this is ASCII string"
True
>>> s == "This Is Ascii String"
False
>>> a = [1, 2, 3, 4]
>>> a == [1, 2, 3, 4]
True
>>> a == [1, 2, 3]
False

文字列検索と比較

  • find()メソッドを条件に使う
>>> s = "this is ASCII string"
>>> if s.find("ASCII") != -1:
...     print "I found ASCII"
... 
I found ASCII
  • inを使った記述
>>> s = "this is ASCII string"
>>> if "ASCII" in s:
...     print "I found ASCII"
... 
I found ASCII

型を変換してから比較

>>> numone = 1
>>> strone = "1"
>>> numone == strone
False
>>> str(numone) == strone
True
>>> numone == int(strone)
True
>>> [1, 2, 3] == (1, 2, 3)
False

range()関数で作成したリストをfor文に使う

>>> seq = range(10)
>>> seq
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for item in seq:
...     print item
... 
0
1
2
3
4
5
6
7
8
9

条件の記述にrange()関数を使う

>>> for cnt in range(10):
...     print cnt
... 
0
1
2
3
4
5
6
7
8
9

「開始」や「ステップ」引数を使用した例

>>> for cnt in range(100,110):
...     print cnt
... 
100
101
102
103
104
105
106
107
108
109
>>> for cnt in range(0,10,2):
...     print cnt
... 
0
2
4
6
8

辞書をfor文の条件に使う

>>> rssitem = {"title"  :u"Pythonを勉強中",
...             "link"  :"http://host.to/blog/entry",
...             "dc:date":"2006-05-16T13:24:04Z",
...             "dc:date":"2006-05-16T13:24:04Z",
...             "comment":5}
>>> validattrs = ["title", "link", "dc:date"]
>>> rsskeys = rssitem.keys()
>>> for key in rsskeys:
...     if key not in validattrs:
...             del rssitem[key]
... 
>>> rssitem.keys()
['dc:date', 'link', 'title']

while文の例

>>> cnt = 0
>>> while cnt < 10:
...     print cnt
...     cnt += 1
... 
0
1
2
3
4
5
6
7
8
9

while文でdo〜while文を表現する

>>> cnt = 0
>>> while True:
...     print cnt
...     cnt += 1
...     if cnt >= 9:
...             break
... 
0
1
2
3
4
5
6
7
8