python下for循环的几个小程序

 1、打印乘法口诀表

for i in range(1,10):
    for j in range(1,i+1):
        print("%dx%d=%d"%(j,i,i*j),end =" ")
    print("")
print("*******************************************")
for i in range(9,0,-1):
    for j in range(1,i+1):
        print("%dx%d=%d"%(j,i,i*j),end =" ")
    print("")
print("*************************************************")
for i in range(9,0,-1):
    for j in range(i,0,-1):
        print("%dx%d=%d"%(j,i,i*j),end =" ")
    print("")
运行结果如下


1x1=1 
1x2=2 2x2=4 
1x3=3 2x3=6 3x3=9 
1x4=4 2x4=8 3x4=12 4x4=16 
1x5=5 2x5=10 3x5=15 4x5=20 5x5=25 
1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36 
1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49 
1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64 
1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81 
*******************************************
1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81 
1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64 
1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49 
1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36 
1x5=5 2x5=10 3x5=15 4x5=20 5x5=25 
1x4=4 2x4=8 3x4=12 4x4=16 
1x3=3 2x3=6 3x3=9 
1x2=2 2x2=4 
1x1=1 
*************************************************
9x9=81 8x9=72 7x9=63 6x9=54 5x9=45 4x9=36 3x9=27 2x9=18 1x9=9 
8x8=64 7x8=56 6x8=48 5x8=40 4x8=32 3x8=24 2x8=16 1x8=8 
7x7=49 6x7=42 5x7=35 4x7=28 3x7=21 2x7=14 1x7=7 
6x6=36 5x6=30 4x6=24 3x6=18 2x6=12 1x6=6 
5x5=25 4x5=20 3x5=15 2x5=10 1x5=5 
4x4=16 3x4=12 2x4=8 1x4=4 
3x3=9 2x3=6 1x3=3 
2x2=4 1x2=2 
1x1=1 

2、打印100内的所有质数

for i in range(2,101):
    for j in range(2,i):
        if i % j == 0:
            break
    else:
        print(i,end=' ')

运行结果:

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

3、用*打印金字塔

#金字塔顺打
for i in range(1,5):
    print(" "*(4-i)+"*"*(2*i-1))
print("------------------------------------------------")
#倒打
for m in range(4,0,-1):
    print(" " * (4 - m) + "*" * (2 * m - 1))


 

运行结果:

  *
  ***
 *****
*******
------------------------------------------------
*******
 *****
  ***
   *
注:两段代码同时执行可打印菱形

 4、输出所有水仙花数

m =[]
for i in range(100,1000):
    a = i//100
    b = i%100//10
    c = i%10
    if i == a**3+b**3+c**3:
        m.append(i)
print(m)

 

 运行结果:

[153, 370, 371, 407]

5、输出所有五位数的回文数

for n in range(10000,1000000):
    a = n // 10000
    b = n % 10000 // 1000
    c = n % 100 // 10
    d = n % 10
    if a == d and b == c:
        print(n)
   

 

 

 

 

你可能感兴趣的:(python)