用書 PYTHON王者歸來 作者洪錦魁
巢狀迴圈
for i in range(1,10):
for j in range (1,10):
result = i*j
print(f”{i}*{j}= {result:<3d}”,end=””)
print()

執行結果

for i in range(1,10):
for j in range(1,10):
if j<i:
print(“aa”,end=””)
print()

執行結果

end=”” 意思是python輸出不換行,沒加會變以下


執行結果

break
for a in range(1,10):
if a==5:
break
print(a,end=”,”)
print()
for b in range(0,11,2):
if b==6:
break
print(b,end=”,”)
print()

執行結果

若中間沒有 print() 則會連一起

names=[“Lisa”,”Jenny”,”Jane”,”Kenny”,”Barbala”,”Susan”]
n=int(input(“Please input a numebr:”))
if n > len(names): n= len(names)
index=0
for name in names:
if index ==n:
break
print(name,end=” “)
index+=1

執行結果

分數前五高
scores =[100,85,90,77,32,85,45,60,99,96]
scores.sort(reverse=True)
count = 0
for score in scores:
count+=1
print(score, end=” “)
if count == 5:
break

執行結果

COUNTIUE
for var in vars
1
if 若條件式是True 則不執行第三
2
continue
3
scores =[100,85,90,77,32,85,45,60,99,96]
count = 0
for score in scores:
if score <= 90:
continue
count+=1
print(f”超過90分的有{count}人”) 沒被執行的有幾個

執行結果

students=[[“Amy”, 100], [“Candy”, 90], [“Susan”, 55], [“Nini”, 98], [“Quen”, 66], [“peggy”, 85],]
for student in students:
if student[1] > 90:
continue
print(student)

執行結果
除了100和98 其他都沒有被執行所以列出未執行的


執行結果
除了55,66和85 其他都沒有被執行所以列出未執行的

For ….. else 迴圈(質數)
n = int(input(“Please input a number:”))
if n == 2:
print(f”{n} is質數”)
else:
for num in range(2,n): #過濾掉1
if n % num ==0:
print(f”{n} is not 質數”)
break
else:
print(f”{n} is 質數”)

執行結果

