語句:
if 條件表達式:
code1
code2
當條件表達式成立時,返回True,執行對應的代碼塊python
job = "programmer" if job == "programmer": print("錢多") print("話少") print("*的早")
語句:
if 條件表達式:
code1 ..
else:
code2 ...code
job = "programmer" if job == "programmer": print("錢多") print("話少") print("*的早") else: print("給你小紅花兒~")
語句:
if 條件表達式1:
code1
elif 條件表達式2:
code2
elif 條件表達式3:
code3
else:
code4對象
money = False car = False house = False if money == True: print("你是土豪麼???") elif car == True: print("你是有一輛蹦蹦嘛???") elif house == True: print("你是什麼房子啊?") else: print("你是個好人~")
單項分支,雙向分支,多項分支的互相嵌套組合it
money = False car = True house = True if money == True: print("你是土豪麼???") if house == True: print("你是什麼房子啊?") if car == True: print("你是有一輛蹦蹦嘛???") else: print("其實還能夠~") else: print("感受差點意思~") else: print("你是個好人~")
# 打印1~100全部數字 i = 1 while i <= 100: print(i) i += 1
# 打印1~100的累加和 i = 0 total = 0 while i <= 100: total += i i += 1 print(total)
while True: print("死循環")
while True: pass
# 1~10,遇到5終止循環 i = 1 while i <= 10: print(i) if i == 5: break i += 1
# 打印1~100中不含4的數字 i = 1 while i <= 100: strvar = str(i) if "4" in strvar: i += 1 continue print(i) i += 1
循環/遍歷/迭代,把容器中的元素一個個取出來for循環
# Error # setvar = {"a", "b", "c"} # i = 0 # while i < len(setvar): # print(setvar[i]) # i+=1
for 變量 in Iterable:
code1class
Iterable可迭代性數據效率
range(開始值,結束值,步長)
區間爲[開始值,結束值),爲左閉右開區間,右邊的結束值取不到容器