Python註釋、分支結構、迴圈結構、偽“選擇結構”用法例項分析
阿新 • • 發佈:2020-01-10
本文例項講述了Python註釋、分支結構、迴圈結構、偽“選擇結構”用法。分享給大家供大家參考,具體如下:
註釋:
python使用#作為行註釋符,使用三引號作為多行註釋符
分支結構:
if-else:
a=int(input("你的成績是:")) if a>60: print("你合格了!") else : print("你沒及格!")
if-elif-else:
a = int(input("請輸入一個整數")) if a<0: print("0>") elif a<10:#elif=else if print("<10") elif a<60: print("a<60") else : print("a>60")
迴圈結構:
for:
list1 = ["apple","banana","pine","super banana"] for i in list1: print(i,end="\t") for i in range(10): print(i,end="\t") print("\n------迭代同時顯示下標------") for i,value in enumerate(['A','B','C']): print(i,value) print("\n------for-else------") for i in range(0,10,3): print(i) else:#執行完for就執行else print("你跳出了迴圈")
結果:
apple banana pine super banana 0 1 2 3 4 5 6 7 8 9 ------迭代同時顯示下標------ 0 A 1 B 2 C ------for--else------ 0 3 6 9 你跳出了迴圈
while:
n=3 while n>0: print("hello world",n) n=n-1 def while_else(count): while count>3: print("in while") count=count-1 else: print("你退出了迴圈") while_else(0)#不進入while while_else(5)#進入while
程式碼結果:
hello world 3 hello world 2 hello world 1 --------------------------- 你退出了迴圈 in while in while 你退出了迴圈
迴圈控制語句:
break:跳出當前迴圈
continue:提前結束此次迴圈
while n!=1: n=int(input("你猜:")) if n == 10: print("right") break elif n > 10 : print("too big") else : print("too small") else : print("你退出了迴圈")
num=10 while(num>0): if num %2==0: print(num,end='') num = num - 1 else: print(num,end='') print('-',end='') num=num-1 continue print('+',end='')
偽“選擇結構”:
知乎:Python中為什麼沒有switch語法結構,有什麼代替方案嗎?
switch結構是向下逐一比對直到找到指定選擇來執行,如果是比較多的選項的話,需要比較多查詢時間(雖然單使用者處理裡面不在意這點時間),
而字典構成的偽“選擇結構”,使用的是hash查詢,雜湊值的計算是比較快的,查詢時間比switch少(多使用者更有優勢?)
更多關於Python相關內容可檢視本站專題:《Python列表(list)操作技巧總結》、《Python字串操作技巧彙總》、《Python資料結構與演算法教程》、《Python函式使用技巧總結》、《Python入門與進階經典教程》及《Python檔案與目錄操作技巧彙總》
希望本文所述對大家Python程式設計有所幫助。