1. 條件判斷
計算機之所以能做很多自動化的任務,就是因為它可以自己做條件判斷腊满。每種語言都離不開條件判斷验残,無非是語法不一致而已五慈。故此處只給出具體實例铺遂,不做過多講解。
# eg1 if ... else ...
>>> age = 3
>>> if age >= 18:
... print('your age is',age)
... print('adult')
... else:
... print('your age is',age)
... print('teenager')
...
('your age is', 3)
teenager
# eg2 if ... elif ... else ...
>>> age = 3
>>> if age >= 18:
... print('adult')
... elif age >= 6:
... print('teenager')
... else:
... print('kid')
...
kid
2. 循環(huán)
- Python循環(huán)有兩種士袄,一種是for...in循環(huán)悲关,依次把list或tuple中的每個元素迭代出來【類似PHP中的foreach】,for X in ...循環(huán)就是把每個元素代入變量谎僻,然后執(zhí)行縮進塊的語句
# 例1
>>> names = ['liheng','wenxiu','yuling']
>>> for name in names:
... print(name)
...
liheng
wenxiu
yuling
# 例2
>>> s = 0
>>> for i in (1,2,3,4,5):
... s = s + i
...
>>> print(s)
15
- 知識點:range()函數(shù),可以生成一個整數(shù)序列寓辱,再通過list()函數(shù)可以轉(zhuǎn)換為list
>>> range(5)
[0, 1, 2, 3, 4]
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> sum = 0
>>> for i in list(range(5)):
... sum = sum + i
...
>>> print(sum)
10
- 第二種是while循環(huán)艘绍,只要條件滿足就不斷循環(huán),條件不滿足就退出循環(huán)
>>> s = 0
>>> n = 99
>>> while n > 0:
... s = s + n
... n = n - 2
...
>>> print s
2500
- 知識點: break 和 continue 語句讶舰,與其他語言相似鞍盗,不再贅述
while n < 100:
... n = n + 1
... if n % 2 == 0:
... continue
... print(n)
...
1
3
5
7
9
11
13
15
17
19
21
23
25
27
29
31
33
35
37
39
41
43
45
47
49
51
53
55
57
59
61
63
65
67
69
71
73
75
77
79
81
83
85
87
89
91
93
95
97
99