用python中的数字乘以数字1,但只能乘以美国给定的特定数字

2024-09-30 01:27:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须定义一个过程,它将一个正整数作为输入,并打印出一个乘法表,显示输入数字之前的所有整数乘法。 例如,我需要这个输出:

print_multiplication_table(2)

1 * 1 = 1

1 * 2 = 2

2 * 1 = 2

2 * 2 = 4

所以我试过了:

def print_multiplication_table(n):
    count=0
    multiplicador=n
    while count<multiplicador:
        count+=1
        print n,"x", count, "=", n*count

    def print_multiplication_table(n):
        num=1
        print str(num) + ' * ' + str(num) + ' = ' + str(num*num)
        while num<n:
            siguiente=num+1
            conteo=num-1
            while conteo<n:
                print str(num) + ' * ' + str(siguiente) + ' = ' + str(num*siguiente)
                print str(num) + ' * ' + str(siguiente) + ' = ' + str(num*siguiente)

但这会产生一个永远运行的循环,我不知道如何让它停止。在

然后我尝试了另一种更优雅的方法,比如:

^{pr2}$

但是它没有考虑我要乘的那个数之前的乘法(输出是2x1=2,2x2=4,但不乘以1x1,也不乘以1x2)。在

我需要做些什么改变?有什么提示吗? 谢谢!在


Tags: 定义过程defcounttablenumprint乘法
3条回答

使用生成器表达式:

r = xrange(1, n+1)
g = (' '.join([str(i), '*', str(j), '=', str(i*j)]) for i in r for j in r)
print ('{}\n'*n*n).format(*g)

最简单的方法是:

from itertools import product

def pmt(n):
    for fst, snd in product(xrange(1, n + 1), repeat=2):
        print '{} * {} = {}'.format(fst, snd, fst * snd)

pmt(2)

1 * 1 = 1
1 * 2 = 2
2 * 1 = 2
2 * 2 = 4

这里需要一个嵌套的for循环。在

>>> def print_multiplication_table(n):
        for i in xrange(1, n+1):
            for j in xrange(1, n+1):
                print "{}x{}={}".format(i, j, i*j)


>>> print_multiplication_table(2)
1x1=1
1x2=2
2x1=2
2x2=4

您的while循环不起作用,因为您从1到数字,并且只将数字与count相乘,因此生成一个类似10x1, 10x2, 10x3...的序列。在

相关问题 更多 >

    热门问题