分支與迴圈(2)
阿新 • • 發佈:2020-12-07
1.while迴圈
#語法:while 條件塊:(如果條件永遠為真就會死迴圈) # 語句塊: i=1 sum=0 while i<=10: sum += i i += 1 print(sum) # while True: anwer=input("輸入數字") if anwer=="9": break #break跳出整個迴圈體,continue跳出當前迴圈,進入下一個迴圈 i=10 while i < 20: i += 1 if i%2==0: continue else:print(i) j=0 # while j<5: if j<5: print(j) j+=1 else: print(6)
2.for迴圈
#for迴圈 #for 變數 in 可迭代物件: # 語句塊: for each in "fince": print(each) #while寫法(len()獲取物件長度) k=0 while k <len("fince"): print("fince"[k]) k +=1 #1-100和(range生成數字數列 range(stop),range(start,stop),range(start,stop.step))sun=0 for i in range(1,101): sun += i print(sun) for j in range(1,10,2): print(j) #素數不能被二整除的數 for n in range(2,10): for x in range(2,n): if n % x == 0: print(n,"=",x,"*",n // x) break else: print(n,"是素數")
九九乘法表
for i in range(1,10): for j in range(1,i+1):if j<=10: print(j, "*", i, "=", i * j, end="\t ") else: print() print()
i=1 while i<10: j=1 while j<=i: print(j,"*",i,"=",j*i,end='\t') j+=1 print() i+=1