1.if條件語句
1.1 簡單的if語句:單分支if語句
>>> age = 18
>>> if age >=18:
... print("You are an adult!")
...
You are an adult!
1.2 if-else語句:雙分支if語句
>>> age = 17
>>> if age >= 18:
... print("You are an adult!")
... else:
... print("Sorry, you are too young!")
...
Sorry, you are too young!
雙分支if-else語句類似於三目運算符。如果條件(緊跟在if後面)爲真,表達式的結果爲提供的第一個值,否則爲第二個值(else之後的值)。
>>> age = 17
>>> print("You are an adult ") if age >= 18 else print("Sorry, you are too young!")
Sorry, you are too young!
1.3 if-elif-else語句:多分支if語句
要檢查多個條件,可使用elif。elif是else if的縮寫,由一個if子句和一個elseelse子句組成,也就是包含條件的else子句。elif語句可以有多個,但else語句至多有一個。
>>> grade = int(input("Please input a grade:"))
Please input a grade:88
>>> if 0 <= grade < 60:
... print("Fail")
... elif 60 <= grade < 75:
... print("Pass")
... elif 75 <= grade < 85:
... print("Well")
... elif 85 <= grade < 100:
... print("Excellent")
... else:
... print("Invalid input!!")
...
Excellent
1.4 if語句嵌套
例如查看16是否能被2和4整除
>>> num = 16
>>> if num % 2 == 0:
... if num % 4 == 0:
... print("{} can divisible by 2 and 4".format(num))
... else:
... print("{} can divisible by 2,not by 4".format(num))
... else:
... print("{} cann't divisible by 2")
...
16 can divisible by 2 and 4
2. 循環語句
2.1 while循環
while循環不斷地運行,直到指定地條件不滿足爲止。
注意,在Python中,沒有do…while循環。
while 條件:
語句
>>> current_number = 1
>>> while current_number <= 5:
... print(current_number)
... current_number += 1
...
1
2
3
4
5
(1)while循環使用else語句
while 條件:
代碼塊1
else:
代碼塊2
while循環使用else之後語句,只有在循環正常結束時纔會執行。若while循環在執行過程中中斷了,也即是說執行了break語句,這裏的else語句就不會被執行。
i = 0
while i < 5:
print(i)
i += 1
else:
print("循環完畢")
ycy@ubuntu18:~$ python3 while_else.py
0
1
2
3
4
循環完畢
2.2 for循環
for 變量 in 可迭代對象:
代碼塊1
else:
代碼塊2
用for循環實現爲可迭代對象中每個元素執行代碼塊。
>>> numbers = ['1', '2', '3', '4']
>>> for i in numbers:
... print(i)
...
1
2
3
4
(1)range()函數
Python內置了一個創建分爲的函數range()。範圍類似於切片。其包含起始位置,但不包含結束位置。
>>> range(5)
[0, 1, 2, 3, 4]
>>> range(0, 5)
[0, 1, 2, 3, 4]
>>> range(2, 5)
[2, 3, 4]
>>> range(0, 5, 2)
[0, 2, 4]
使用range()函數來創建一個列表
>>> list(range(5))
[0, 1, 2, 3, 4]
(2)for循環嵌套
for循環打印99乘法表
for i in range(1,10):
for j in range(1, i+1):
print(str(i)+"*"+str(j)+"="+str(i*j),end='\t')
print()
(3)for循環使用else語句
for循環之後也可使用else語句,用法同while。
li = [1, 2, 3, 4, 5]
for i in li:
print(i)
else:
print("循環結束")
ycy@ubuntu18:~$ python3 for_else.py
1
2
3
4
5
循環結束
3. 跳出循環
(1)break:用來跳出整個當前循環。
li = [1, 2, 3, 4, 5]
for i in li:
if i == 3:
break
print(i)
ycy@ubuntu18:~$ python3 break.py
1
2
(2)continue用來結束當前迭代,並跳到下一次迭代開頭。這意味着跳過循環體中餘下的語句,但不結束循環。
li = [1, 2, 3, 4, 5]
for i in li:
if i == 3:
continue
print(i)
ycy@ubuntu18:~$ python3 contine.py
1
2
4
5
注:多層循環地跳出可以使用標誌位
4. pass語句
pass語句什麼也不做。當語法上需要語句但程序不需要動作時,可以使用它。
可以後期添加代碼,也可用於調試,語法上是不會報錯的。
>>> for i in range(5):
... pass
...