https://www.cnblogs.com/evablogs/p/6691776.html
条件判断
简单if语句
1
2
3
4
5
|
>>>name = 'lily' >>> if name = 'lily' : print 'hello,' , name hello,lily |
if-else
1
2
3
4
5
6
7
|
>>>score = 90 >>> if score> = 80 : print 'very good' else : print 'keep trying' very good |
if-elif-else
1
2
3
4
5
6
7
8
9
|
>>> age = 18 >>> if age> = 18 : print 'adult' elif age< 18 : print 'teenager' else : print 'please enter the correct age' adult |
循环
for
1
2
3
4
5
6
7
8
9
|
>>> L = [ 1 , 2 , 3 , 4 , 5 ] >>> for v in L: print v 1 2 3 4 5 |
while
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
>>> a = 0 >>> while a< 10 : a = a + 1 print a 1 2 3 4 5 6 7 8 9 10 |
退出循环
break与continue区别:
break:退出循环体
利用 while True 无限循环配合 break 语句,计算 1 + 2 + 4 + 8 + 16 + ... 的前20项的和。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
>>> s = 0 >>> x = 1 >>> n = 1 >>> while True : if n> 20 : break s = s + x x = x * 2 n = n + 1 print s 1 3 7 15 31 63 127 255 511 1023 2047 4095 8191 16383 32767 65535 131071 262143 524287 1048575 |
continue:退出本次循环,不执行此次循环的循环体,继续下一个循环
1
2
3
4
5
6
7
8
9
10
11
12
|
>>> b = [ 0 , 1 , 2 , 6 , 3 , 4 , 1 , 5 ] >>> for v in b: if v< 2 : continue print v 2 6 3 4 5 |