Python循環(huán)
Python循環(huán)
while
#語(yǔ)法:
while condition:
block #當(dāng)條件滿足即condition為True,進(jìn)入循環(huán)體,執(zhí)行block
#舉例:
flag=10
while flag:
print(flag)
flag -= 1
#如果flag=-10:
flag=-10
while flag:
print(flag)
flag += 1
for
for element in itratable:
block #當(dāng)?shù)鷮?duì)象中有元素可以迭代,進(jìn)入循環(huán)體,執(zhí)行block
range函數(shù)
前包后不包range(10) 從0開始不包括末尾的10
for i in range(10):
print(i+1)
#倒敘打印
for i in range(10,0,-1):
print(i)
continue
[中斷當(dāng)前循環(huán)的當(dāng)次執(zhí)行,繼續(xù)下一次循環(huán)]
#舉例:計(jì)算10以內(nèi)的偶數(shù)
#方法1
for i in range(0,11,2):
if i != 0:
print(i)
#方法2:
for i in range(11):
if i%2 == 0 and i != 0:
print(i)
break
[終止bread所在整個(gè)循環(huán)]
#測(cè)試break范圍:
for i in range(2):
for j in range(10):
if j < 2:
print(j)
else:
break
print(“aaa”)
0
1
aaa
0
1
aaa `由此結(jié)果證明break范圍為所在循環(huán)`
練習(xí):
#給定一個(gè)不超過5位的正整數(shù),判斷其有幾位,依次打印出個(gè)位、十位、百位、千位、萬位的數(shù)字
Input_Num=int(input(“Please input integer number:”))
for i in range(len(Input_Num)): #取出數(shù)字長(zhǎng)度決定循環(huán)次數(shù)
n=Input_Num%10 #將最后一位取出
Input_Num//=10 #將取出后的剩余數(shù)字賦值
print(n) #打印最后一位
y=int(input(“hehhe:”))#邏輯與上面for循環(huán)類似
Num_len=4
while Num_len != 0:
n=y%10
y//=10
print(n)
Num_len-=1
循環(huán)else字句:
如果循環(huán)正常的執(zhí)行結(jié)束,就執(zhí)行else字句,如果使用break終止,else字句不會(huì)執(zhí)行
#語(yǔ)法:
while condition:
block
else:
block
for element in iteratable:
blcok
else:
block
help(函數(shù)名稱)[]help(range)],查看函數(shù)幫助
練習(xí)
- 打印一個(gè)邊長(zhǎng)為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èi)所有奇數(shù)的和
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 #將階乘結(jié)果賦予a
b += a #將每個(gè)階乘的結(jié)果累加賦予b
pirnt(b)
- 給一個(gè)數(shù),判斷它是否是素?cái)?shù)(質(zhì)數(shù)):一個(gè)大于1的自然數(shù)只能被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):#循環(huán)9列
for j in range(1,10):#每行打印結(jié)果循環(huán)
if j <= i:#判斷打印區(qū)間
print(j,”*”,i,”=”,j*i, end = ” “)
print(” “)
- 打印100以內(nèi)的斐波那契數(shù)列
a=0
b=1
while True:
x=a+b
if x<100:
print(x)
else:
break
a=b
b=x
- 求斐波那契數(shù)列第101項(xiàng)
a=0
b=1
c=0
while True:
x=a+b
a=b
b=x
c+=1#計(jì)數(shù)器
if c == 100:
print(x)
break
- 求10萬內(nèi)的所有素?cái)?shù)
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”)