前面的學習過程中,我們都是在IDLE中運行單條的代碼。但在編程過程中,我們可能希望在某時重復執行某條代碼,或選擇性執行某幾條代碼等。此時,我們便需要借助流程控制語句來實現對程序運行流程的選擇、循環和返回等進行控制。
*****
[TOC]
****
# 3.1 布爾值與布爾操作符和比較操作符
**布爾(Boolean)數據類型** 只有兩種值:True 和 False。
```
>>> test = True
>>> test
True
>>> True
True
>>> true
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
true
NameError: name 'true' is not defined
>>> True = False
SyntaxError: can't assign to keyword
```
如上:兩種布爾值,首字母必須大寫,它們是關鍵字,不可用作變量名。
**布爾操作符和比較操作符**
布爾操作符:
```
>>> True and True
True
>>> True and False
False
>>> False or True
True
>>> False or False
False
>>> not True
False
>>> not False
True
```
比較操作符:
```
>>> 100 == 100
True
>>> 23 > 32
False
>>> 'hello' == 'hello'
True
>>> 'Hello' == 'hello'
False
>>> True != False
True
>>> 55 == 55.0
True
>>> 55 == '55'
False
```
混合布爾和比較操作符:
```
>>> (2 < 5) and (6 < 7)
True
>>> (2 < 5) and (6 < 4)
False
>>> (1 == 2) or (2 == 2)
True
>>> 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2
True
```
****
# 3.2 代碼塊與作用域
在 Python 中,通過縮進來表示代碼塊和作用域,即相同縮進范圍內的代碼在一個代碼塊和作用域中,且同一代碼塊和作用域中不能有不同的縮進。Python 中用冒號“:”標記同一代碼塊。如下:
```
if True:
print('Hello')
print('Python')
```
在使用代碼塊的過程中,可以用 `pass` 占位符來占據代碼塊位置,以便后續添加代碼。如下:
```
if True:
pass
```
****
# 3.3 if 語句
**簡單的 if 語句:**
語法:
```
if conditional_test:
do something
```
示例:
```
age = input('請輸入你的年齡:')
if int(age) >= 18:
print('恭喜你,你成年了哎。')
```
```
# Out:
請輸入你的年齡:19
恭喜你,你成年了哎。
```
**if-else 語句:**
語法:
```
if conditional_test:
do something
else:
do other thing
```
示例:
```
name = input('Please type your name:')
if name == 'your name':
print('Success.')
else:
print('Error.')
```
```
# Out:
Please type your name:your name
Success.
```
**if-elif-else 結構:**
示例:
```
num = 66
guessNum = int(input('請輸入你猜測的數字: '))
if guessNum < num:
print('猜小了。')
elif guessNum == num:
print('猜對了。')
elif guessNum > num:
print('猜大了。')
else:
print('你看不到我!')
```
**if三元操作符**
```
x = int(input('Please input a number for x:'))
y = int(input('Please input a number for y:'))
smaller = x if x < y else y
print('The smaller number is:', smaller)
```
```
# Out:
Please input a number for x:16
Please input a number for y:15
The smaller number is: 15
```
****
# 3.4 while 循環
語法:
```
while expression:
repeat_block
```
其語意為:判斷 expression 表達式,如果表達式為真,則執行 repeat_block 并再次判斷 expression,直到 expression 返回假為止。
示例:
```
i = 1
while i <= 5:
print('第' + str(i) + '遍:')
print('Hello Python!\n')
i += 1
```
```
# Out:
第1遍:
Hello Python!
第2遍:
Hello Python!
第3遍:
Hello Python!
第4遍:
Hello Python!
第5遍:
Hello Python!
```
*如果 expression 一直為真,程序將永遠無法退出 repeat_block 的執行,即陷入死循環。*
****
# 3.5 for 循環
語法:
```
for element in iterable:
repeat_block
```
`for/in` 是關鍵字,語意為:針對 iterable 中的每個元素執行 repeat_block,在 repeat_block 中可以使用 element 變量名來訪問當前元素。iterable 可以是Sequence序列類型、集合或迭代器等。
循環讀取列表元素:
```
fruits = ['apple', 'banana', 'orange', 'pear', 'grape']
for fruit in fruits:
print('Current fruit is: ', fruit)
```
```
# Out:
Current fruit is: apple
Current fruit is: banana
Current fruit is: orange
Current fruit is: pear
Current fruit is: grape
```
循環讀取字典元素:
```
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
for key in d:
print(key)
print('\n******\n')
for key in d.keys():
print(key)
print('\n******\n')
for value in d.values():
print(value)
print('\n******\n')
for key, value in d.items():
print(key, "::", value)
```
```
# Out:
a
b
c
d
******
a
b
c
d
******
1
2
3
4
******
a :: 1
b :: 2
c :: 3
d :: 4
```
****
# 3.6 else 子句
for和while復合語句可以選擇使用else子句(實際上,這種用法相當少見)。
else子句只在for循環通過迭代結束后執行,或在while循環通過其條件表達式變為False終止后執行。
```
for i in range(3):
print(i)
else:
print('done')
```
```
# Out:
0
1
2
done
```
```
i = 0
while i < 3:
print(i)
i += 1
else:
print('done')
```
```
# Out:
0
1
2
done
```
****
# 3.7 break 和 continue
`break語句`:在循環中,如果執行到了 break 語句,將結束該循環。
```
i = 0
while i < 8:
print(i)
if i == 4:
print("Breaking from loop")
break
i += 1
```
```
# Out:
0
1
2
3
4
Breaking from loop
```
`continue語句` :在循環中,如果執行到了 continue 語句,將跳回到循環開始處,重新對循環條件求值。
```
for i in (0, 1, 2, 3, 4, 5):
if i == 2 or i == 4:
continue
print(i)
```
```
# Out:
0
1
3
5
```
****
# 3.8 語句嵌套
Python 中,if、while、for等語句可相互嵌套。
如下,實現一個簡單的排序算法:
```
lst = [2, 3, 0, -12, 55, 7, 4, 66]
print('Before sorting:')
print(lst)
lenLst = len(lst)
for i in range(0, lenLst - 1):
for j in range(i + 1, lenLst - 1):
if lst[i] > lst[j]:
lst[i], lst[j] = lst[j], lst[i]
print('After sorting:')
print(lst)
```
```
# Out:
Before sorting:
[2, 3, 0, -12, 55, 7, 4, 66]
After sorting:
[-12, 0, 2, 3, 4, 7, 55, 66]
```