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. 循环
- Python循环有两种,一种是for...in循环,依次把list或tuple中的每个元素迭代出来【类似PHP中的foreach】,for X in ...循环就是把每个元素代入变量,然后执行缩进块的语句
# 例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()函数,可以生成一个整数序列,再通过list()函数可以转换为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循环,只要条件满足就不断循环,条件不满足就退出循环
>>> 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
网友评论