如何推广乘法表到(n * m)
我有这个:
def print_multiples(n):
i = 1
while i <= 10:
print n * i,
i += 1
print
i = 1
while i <= 10:
print_multiples(i)
i += 1
我需要把这个程序做得更通用一些,让它可以生成一个(n * m)的乘法表。老实说,我其实不知道在实际操作中“通用化一个表”是什么意思,虽然我在理论上是懂的。我只是不确定我需要把哪些整数改成变量,或者这是不是我该走的方向……
1 个回答
0
你可以这样写你的函数:
def print_multiples(n, m = 10):
for i in range(0, m + 1):
print n * i,
print ""
然后
print_multiples(2)
将会打印出
0 2 4 6 8 10 12 14 16 18 20
并且
print_multiples(2, 5)
0 2 4 6 8 10
接着用这个函数:
def print_table(n = 10):
for i in range(1, n + 1):
print_multiples(i)
你可以:
print_table()
这样会产生以下输出:
0 1 2 3 4 5 6 7 8 9 10
0 2 4 6 8 10 12 14 16 18 20
0 3 6 9 12 15 18 21 24 27 30
...
0 10 20 30 40 50 60 70 80 90 100
而
print_table(2)
则会产生:
0 1 2 3 4 5 6 7 8 9 10
0 2 4 6 8 10 12 14 16 18 20