#shift向右缩进、ctrl+shift向左缩进
for...循环
#范围
for i in range(10):
print("hello,I love this world",i)
#列表
for name in ['alex','peiqi','xiaozhu']:
print(name)
# 打印偶数
# for i in range(100):
# if i % 2 == 0 :
# print(i)
# 打印奇数
# for i in range(100):
# if i % 2 != 0 :
# print(i)
# 打印50以后的偶数
# for i in range(100):
# if i >= 50:
# if i % 2 == 0:
# print(i)
for i in range(50,100):
if i % 2 == 0:
print(i)
#倒序
for i in range(100,50,-1):
if i % 2 == 0:
print(i)
二、嵌套for循环
建议:嵌套不超过4层
for floor in range(1,7):
print(f"当前在{floor}层".center(50,'-'))
for room in range(1,10):
print(f"当前房间是{floor}0{room}室.")
三、break & continue
continue #停止本次循环,进入下次循环
break #结束整个循环
for floor in range(1,7):print(f"当前在{floor}层".center(50,'-'))
if floor == 3 :
print("不走三层....")
continue #停止本次循环,进入下次循环
for room in range(1,10):
if floor == 4 and room:
print("die at young")
exit() #退出程序
break #结束整个循环
break
print(f"当前房间是{floor}0{room}室.")
打印9x9乘法表
# 第一种# for i in range(1,10):
# for j in range(1,10):
# if j > i:
# print("")
# break
# else:
# # c ='{}x{}={}'.format(i,j,i*j)
# # print(c,end = ' ')
# print(f"{i}x{j}={i * j}",end = ' ')
# 第二种简单
for i in range(1,10):
for j in range(1,i+1):
print(f"{i}x{j}={i*j}",end=" ")
print() # 什么都不写就是一个end="\n"
9x9乘法表 结果如下:
1x1=1
2x1=2 2x2=4
3x1=3 3x2=6 3x3=9
4x1=4 4x2=8 4x3=12 4x4=16
5x1=5 5x2=10 5x3=15 5x4=20 5x5=25
6x1=6 6x2=12 6x3=18 6x4=24 6x5=30 6x6=36
7x1=7 7x2=14 7x3=21 7x4=28 7x5=35 7x6=42 7x7=49
8x1=8 8x2=16 8x3=24 8x4=32 8x5=40 8x6=48 8x7=56 8x8=64
9x1=9 9x2=18 9x3=27 9x4=36 9x5=45 9x6=54 9x7=63 9x8=72 9x9=81
素数:写程序求出100以内的所有素数(如果除了1和它本身以外,不能被其他正整数整除的数)
for i in range(2,101):is_prime_num = True
for j in range(2,i):
if i % j == 0:
is_prime_num = False
if is_prime_num:
print(i,"是素数...")
打印三角形
for i in range(11):if i <= 5:
print(f"* " * i)
else:
print("* " * (10-i))
结果
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*