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”)