8
c +=
i
9
#
a为总和,b为偶数和,c为奇数和,b+c是奇数和偶数和
10
print
(
'
1~100的和:%d
'
% a,
'
\n
'
,
'
1~100的偶数和:%d
'
% b,
'
\n
'
,
'
1~100的奇数和:%d
'
% c,
'
\n
'
,
'
1~100的奇数数+偶数和:%d
'
% (b + c))
运行结果:
2
for
i
in
range(1, 10
):
3
for
j
in
range(1, i+1
):
4
print
(
'
{}x{}={}\t
'
.format(j, i, i*j), end=
''
)
5
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
3、打印直角三角形和倒直角三角形
1 # for循环打印直角三角形
2 for i in range(1, 6):
3 for j in range(1, i + 1):
4 print('* ', end='')
5 print()
7 # 打印倒直角三角形
8 for k in range(6):
9 print('* ' * (6 - k))
运行结果:
4、打印菱形
# 打印菱形
liu = 6
for i in range(liu):
print(' ' * (liu - i), '* ' * i)
for i in range(liu):
print(' ' * i, '* ' * (liu - i))
# 第二种方法
row = 7
s = row // 2 + 1
x = row - s
for i in range(1, s + 1):
for k in range(s - i):
print(' ', end='')
for j in range(i * 2 - 1):
print('*', end='')
print()
for i in range(x):
for j in range(i + 1):
print(' ', end='')
for k in range(x * 2 -1, i * 2, -1):
print('*', end='')
print()
if
i % 2 !=
0:
a
= i // 2 + 2
#
a控制顺序递增的空格打印数量
print
(
"
"
* a,
"
*
"
* (s - i - 1))
#
(s - i - 1)是倒序打印 * 的数量