Python基礎④:程序控制結構

1、分支結構–if語句

1)分支語句模板

if 條件:
	代碼塊
elif 條件:
	代碼塊
...
else:
	代碼塊

2)分支語句例子

age = 18
res = 0  # 變量初始化
if age >22:
	print('可以結婚了’)
elif age>30:
	print('趕緊結婚')
else:
	print('再等等吧')

3)嵌套語句:if語句中有if

age = eval(input("請輸入年齡"))
if age > 18:
	is_public_place = bool(eval(input("公共場合輸入1,非公共場合輸入0")))
	if not is_public_place:
		print("可以抽菸")
	else:
		print("禁止抽菸")
else:
	print("禁止抽菸")

2、遍歷循環–for循環

1)for循環模板

for 元素 in 可迭代對象: # 可迭代對象包括列表/元組/字符串/字典
	執行語句

2)for循環例子
  ① 直接迭代

graduates = ("lilei","hanmeimei","Jim")
for graduate in graduates:
	print("Congratulations, " + graduate)

  ② 變換迭代

students = {201901:'小明',201902:'小紅',201903:'小強'}
for k,v in students.items():
	print(k,v)
# 201901 小明
# 201902 小紅
# 201903 小強
for student in students:
	print(student)
# 201901
# 201902
# 201903

  ③ range()對象

res = []
for i in range(1,10,2): # 左閉右開,每個+2,1/3/5/7/9
	res.append(i**2)
print(res) # [1,9,25,49,81]

3)break和continue
  ① break用於結束整個循環

product_scores = [89,90,99,70,67,78,85,92,77,82]
i = 0
for score in product_scores:
	# 如果低於75的個數超過1個,則不合格
	if score < 75:
		i += 1
	if i == 2:
		print("產品不合格")
		break  # 結束了整個循環,67後面的元素就遍歷不到了

  ② continue用於結束本次循環

product_scores = [89,90,99,70,67,78,85,92,77,82]
for i in range(len(product_scores)):
	# 如果低於75,輸出警告
	if product_scores[i]>=75:
		continue
	print("第{0}個產品,分數爲{1},不合格".format(i,product_scores[i]))

4)for與else的配合

product_scores = [89,90,99,70,67,78,85,92,77,82]
i = 0
for score in product_scores:
	if score < 75:
		i += 1
	if i == 2:
		print("產品不合格")
		break
else:  # for遍歷完之後,如果沒有break,則運行else
	print("產品合格")

3、無限循環–while循環

1)while的一般格式

while 判斷條件:
	執行語句
# 條件爲真,執行語句
# 條件爲假,while循環結束

2)不用while
因爲實際在編程中,while寫的語句都可以改成for循環,這裏偷點懶,之後循環都用for就好。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章