原本緊接列表後面應該時字典的內容,但在這裏,先插入一個編程語言中比較常用的概念:流程控制。編程語言的流程可分爲三種:順序,條件,循環本文依次闡述其在python中的代碼體現形式
順序結構
最常見的就是順序結構,也就是說代碼是逐行執行的,例子
msg = "This is a test string."
print(msg)
nums = [1, 2, 3]
print(nums)
以上代碼會逐句執行,順序結構本身並沒有什麼好講的,主要是條件分支和循環結構
條件分支
很常見的一個問題,滿足某種條件,執行某種操作,這便是條件分支產生的背景
在python中,主要有if
,if-else
,以及if-elif-else
,這說起來比較抽象,下面是用示例來說明
'''
if conditional_test:
do something
'''
test_num = 1
if test_num == 1:
print("test num equals 1")
以上代碼會輸出字符串test num equals 1
,但如果將test_num = 1
改爲test_num = 2
則不會輸出字符串,因爲不滿足判斷條件,類似的
'''
if conditional_test:
do something
else:
do something
'''
test_num = 2
if test_num == 1:
print("test num equals 1")
else:
print(test_num)
滿足判斷條件輸出字符串test num equals 1
,不滿足時候輸出test_num
的值
最後一種,這裏舉個例子(else代碼塊可以沒有)
'''
if conditional_test:
do something
elif conditional_test:
do something
···
else:
do something
'''
test_num = 3
if test_num == 1:
print("test num equals 1")
elif test_num == 2:
print("test num equals 2")
else:
print(test_num)
這裏有一個重要的概念:條件測試,也就是判斷的依據
判斷條件可以是一個,也可以是多個的共同判斷,這裏就需要引入兩個python的關鍵字了:and
和or
,翻譯過來就是與和或。兩個與的判斷都爲True時才返回True,否則返回False。兩個或的判斷只要有一個爲True,則返回True。
另外的一些特殊情況
"" -> False
" " -> True
[] -> False
0 -> False
其他 -> True
檢查某個元素是否在列表中,可以使用in
,返回bool值,與之相對應的,有not in
。例如
name_list = ["Tom", "Tony", "Candy"]
print("Tom" in name_list) # 輸出:True
print("Tim" in name_list) # 輸出:False
print("Tim" not in name_list) # 輸出:True
循環結構
循環語句有for循環和while循環,for循環在列表一節中已經講過,這裏補充while循環
for循環用於針對集合中的每個元素都一個代碼塊,而while 循環不斷地運行,直到指定的條件不滿足爲止。
# 輸出結果爲1,2,3,4,5
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
要退出循環,除了不滿足條件,還可以使用break
語句
# 輸出結果爲1,2
current_number = 1
while current_number <= 5:
if current_number == 3:
break
print(current_number)
current_number += 1
要返回到循環開頭,並根據條件測試結果決定是否繼續執行循環,可使用continue
語句,它不像break
語句那樣不再執行餘下的代碼並退出整個循環。
# 輸出結果爲1,3,5,7,9
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
使用循環時,一定要注意循環的結束條件,不然後造成死循環
循環在列表中的使用
for循環是一種遍歷列表的有效方式,但在for 循環中不應修改列表,否則將導致Python難以跟蹤其中的元素。要在遍歷列表的同時對其進行修改,可使用while 循環。
while遍歷
while name_list:
name = name_list.pop()
while刪除列表所有指定值
while 'Tom' in name_list:
name_list.remove('Tom')