首页 > 解决方案 > 如何使用 for 循环打印乘法表?

问题描述

此函数打印出一个乘法表(其中每个数字是其行的第一个数字与其列顶部的数字相乘的结果)。

预期输出:

1 2 3

2 4 6

3 6 9

我从代码中得到的输出:

2 4 6 

3 6 9 

def multiplication_table(start, stop):
    for x in (start+1,stop):
        for y in range(start,stop+1):
            print(str(x*y), end=" ")
        print()

multiplication_table(1, 3)

如何打印第一行,我做错了什么?

标签: pythonpython-3.x

解决方案


试试这个:

def multiplication_table(start, stop):
    for x in range(start,stop+1):
        for y in range(start,stop+1):
            print(str(x*y), end=" ")
        print()

multiplication_table(1, 3)

输出:

1 2 3 
2 4 6 
3 6 9 

推荐阅读