條件語句
a=input("請輸入數字a的值:\n") a=int(a) #從控制台接收到的都是字符串類型,需要轉換 if a==0: #也可以寫成if(a==0): print("a=0") elif a>0: #注意是elif print("a>0") else: print("a<0")
循環語句
1、while語句
i=1 sum=0 while i<=100: #冒號 sum+=i i=i+1 #注意python中沒有++、--運算符 print(sum)
2、for語句
python中for語句和其他編程語言的for語句大不相同。python中for語句:
for var in eleSet: statements
eleSet指的是元素集,可以是字符串、列表、元組、集合、字典,也可以是range()函數創建的某個數字區間。
使用for語句遍歷字符串、列表、元組、集合、字典:
for ele in "hello": #遍歷字符串的每個字符 print(ele) for ele in [1,2,3]: #遍歷列表、元組、集合中的每個元素 print(ele)
dict={"name":"張三","age":10,"score":90}
#遍歷字典——方式1 for item in dict.items(): #item是元組,(key,value)的形式 print(item) #輸出一個鍵值對 print(item[0],":",item[1]) #輸出key:value
#遍歷字典——方式2 for key in dict.keys(): print(key,":",dict.get(key))
使用for語句遍歷某個數字區間:
for i in range(10): #遍歷[0,10) print(i) for i in range(20,30): #遍歷[20,30) print(i) for i in range(50,100,10): #遍歷50,60,70,80,90,[50,100)上,步長為10 print(i)
"""
range()函數用於產生數列: range([min,]max[,step]) 數字區間是[min,max),max是必須的。缺省min時,默認為0,缺省step時,默認為1。 step支持負數,即負增長。 """
產生指定數字區間上的元素集:
myList=list(range(10)) #強制類型轉換,列表 print(myList) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] myTuple=tuple(range(10)) #元組 print(myTuple) #(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) mySet=set(range(10)) #集合 print(mySet) #{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} myDict=dict.fromkeys(range(10)) #字典 print(myDict) #{0: None, 1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None}
使用for語句+索引遍歷字符串、列表、元組:
myList=["百度","騰旭","阿里"] for i in range(len(myList)): print(i,"\t",myList[i]) """ 0 百度 1 騰旭 2 阿里 """
else語句可以和while語句/for語句配合使用,當整個while/for循環執行完畢后,會執行else語句。
i=1 while i<5: print(i) i=i+1 else: print("i=5") #整個循環執行完畢時,會自動執行else語句塊 print("while over") for i in range(5): print(i) else: print("for over") print("application over")
continue語句:結束當前本次循環
break語句:結束當前循環
這2個語句只能寫在循環體中,不能寫在else語句塊中。
i=1 while i<5: i=i+1 if(i==2): continue print(i) else: print("over")
如果循環被break終止了,則else語句不會被執行:
i=1 while i<5: i=i+1 if(i==5): break else: print("else running...") #如果循環被break終止,else語句塊會被跳過。只要循環中執行了break,else語句塊就不再執行。 print("over") #over
pass語句
pass語句是一個空語句,即什么都不做。
command=input("請輸入指令:\n") if command=="nothing": pass #什么都不做 elif command=="exit": exit() #退出程序 else: print("無法識別的指令")
說明
- python中沒有switch語句、do...while語句。
- python使用縮進來標識語句塊。
- 如果語句塊只有一條語句,可以寫在同一行:
if True:print(True)