else循環字句【每日一個知識點第304期-Python】
#語法:
while condition:
block
else:
block
for element in iteratable:
blcok
else:
block
help(函數名稱)[]help(range)],查看函數幫助
練習
- 打印一個邊長為n的正方形
print(6*”*”)
for i in range(4):
print(“*” + 4*” ” + “*”)
print(6*”*”)
- 打印菱形
n=3
for i in range(1,8,2):
print(n*” “,i*”*”)
n-=1
n=1
for x in range(5,0,-2):
print(n*” “,x*”*”)
n+=1
- 求100以內所有奇數的和
n=0
for i in range(1,100):
if i%2 != 0:
n+=i
print(n)
- 求1到5階乘之和
a=1
b=0
for i in range(1,6):
a *= i #將階乘結果賦予a
b += a #將每個階乘的結果累加賦予b
pirnt(b)
- 給一個數,判斷它是否是素數(質數):一個大于1的自然數只能被1和它本身整除
m=int(input(“please input >1 number:”))
for i in range(2,m):
if m%i == 0:
print(“No”)
break
else:
print(“Yes”)
- 打印九九乘法表
for i in range(1,10):#循環9列
for j in range(1,10):#每行打印結果循環
if j <= i:#判斷打印區間
print(j,”*”,i,”=”,j*i, end = ” “)
print(” “)
- 打印100以內的斐波那契數列
a=0
b=1
while True:
x=a+b
if x<100:
print(x)
else:
break
a=b
b=x
- 求斐波那契數列第101項
a=0
b=1
c=0
while True:
x=a+b
a=b
b=x
c+=1#計數器
if c == 100:
print(x)
break
- 求10萬內的所有素數
import datetime
starttime = datetime.datetime.now()
for i in range(2,100000):
for x in range(2,i):
if i%x==0:
break
else:
print(i)
endtime = datetime.datetime.now()
print (endtime – starttime,”.seconds”)