## 條件判斷和循環
[TOC]
>[info] #### if else, if elif else的使用
* ##### if else
~~~
age = 10
if age > 5 :
print "大于5"
else:
print "小于5"
~~~
* ##### if elif else
~~~
age = 20
if age > 18:
print "你的年齡", age
elif age < 15:
print "小于", 15
else:
print "無"
~~~
* ##### if
~~~
age = 10
if age: #如果age為真則成立
print age
else:
print 'not'
~~~
>[info] #### range, for, while 的使用
* ##### range 的使用
~~~
print range(10)
#結果:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
~~~
* ##### for
~~~
for i in range(5):
print i
~~~
* ##### 帶下標的for
~~~
>>> for i, value in enumerate(['A', 'B', 'C']):
... print i, value
~~~
* ##### 一行寫成的for
~~~
>>>[x for x in range(10) ]
~~~
* ##### 兩層for 一行代碼完成
~~~
>>>[ x + y for x in range(5) for y in range(5)]
~~~
* ##### 循環出目錄
~~~
>>> import os # 導入os模塊,模塊的概念后面講到
>>> [d for d in os.listdir('.')] # os.listdir可以列出文件和目錄
['.emacs.d', '.ssh', '.Trash', 'Adlm', 'Applications']
~~~
* ##### dict的iteritems()可以同時迭代key和value
* for循環其實可以同時使用兩個甚至多個變量,比如dict的iteritems()可以同時迭代key和value
~~~
>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> for k, v in d.iteritems():
... print k, '=', v
...
y = B
x = A
z = C
~~~
* ##### while
~~~
i = 20
while i > 0:
print i
i = i - 1
~~~
>[success] #### int 轉換成數字
~~~
i = "100"
i = int(1)
~~~
* ##### 判斷是不是數字還是字符串
~~~
>>> x = 'abc'
>>> y = 123
>>> isinstance(x, str)
True
>>> isinstance(y, str)
False
~~~