Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将python中的数字从数字1乘以,但仅限于用户给定的特定数字_Python_While Loop - Fatal编程技术网

将python中的数字从数字1乘以,但仅限于用户给定的特定数字

将python中的数字从数字1乘以,但仅限于用户给定的特定数字,python,while-loop,Python,While Loop,我需要定义一个过程,它以一个正整数作为输入,并打印出一个乘法表,显示所有整数的乘法,包括输入数。 例如,我需要以下输出: 打印乘法表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, "="

我需要定义一个过程,它以一个正整数作为输入,并打印出一个乘法表,显示所有整数的乘法,包括输入数。 例如,我需要以下输出:

打印乘法表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)
但这会产生一个永远运行的循环,我不知道如何让它停止

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

def print_multiplication_table(n):
    count=0
    multiplicador=n
    while count<multiplicador:
        count+=1
        print n,"x", count, "=", n*count
但是它没有考虑到在我将输出乘以2x1=2,2x2=4之前的数字的乘法,但是不乘以1x1,也不乘以1x2

我需要做哪些更改?有什么提示吗? 谢谢

这里需要一个嵌套的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到数字,只将数字与计数相乘,因此,生成类似10x1、10x2、10x3……的序列最简单的是:

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

使用生成器表达式:

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)

xrange可以帮助您创建一个临时变量。您的第一个代码永远不会停止,因为conteo在第二个循环中永远不会递增,所以conteoAs虽然我很喜欢itertools,但我认为在建议使用itertools单行程序之前最好先向OP说明当前代码的错误。@Blender,AFAIK已经解释过了。。。所以我想这应该被认为是非课堂的方式。。。