Python for循环重复添加

Reb*_*des 3 python for-loop

我正在尝试创建一个程序,创建一个nx n的乘法表.赋值需要使用重复加法而不是乘法函数.

这是我到目前为止的代码:

def main():
import math
print('Hello!')
n = (abs(eval(input("Enter n for the multiplication table n x n: "))))
n = int(n)
a = 0
for i in range(1,n+1):
    for x in range(1,n+1):
        a = i+a
        print(i,' * ',x,' = ',a)
main()
Run Code Online (Sandbox Code Playgroud)

它给了我这样的输出:

Hello!
Enter n for the multiplication table n x n: 4
1  *  1  =  1
1  *  2  =  2
1  *  3  =  3
1  *  4  =  4
2  *  1  =  6
2  *  2  =  8
2  *  3  =  10
2  *  4  =  12
3  *  1  =  15
3  *  2  =  18
3  *  3  =  21
3  *  4  =  24
4  *  1  =  28
4  *  2  =  32
4  *  3  =  36
4  *  4  =  40
Run Code Online (Sandbox Code Playgroud)

输出显然不正确,那么我可以更改/添加什么来修复计算?

Unk*_*ble 5

a嵌套for循环中有一个变量,可以为乘法表的不同值连续添加值.让我们不要添加ia每次迭代中a = i*x.这将为您提供正确的乘法值.但是,如果你真的想重复添加它a = 0,请在第二个for循环外部设置,但在第一个内部设置,如下所示:

for i in range(1,n+1):
    for x in range(1,n+1):
        a = i+a
        print(i,' * ',x,' = ',a)
    a = 0
Run Code Online (Sandbox Code Playgroud)