Python 2.7:循环错误,需要建议

时间:2013-08-15 15:03:16

标签: python python-2.7 while-loop

我在Python 2.7中遇到while循环的小问题。

我已经定义了一个过程print_multiplication_table,它将一个正整数作为输入,并打印出一个乘法,表显示所有整数乘法,包括输入数。

这是我的print_multiplication_table功能:

def print_multiplication_table(n):
    count =  1
    count2 = 1
    result = count * count2
    print 'New number: ' + str(n) 
    while count != n and count2 != n:
        result = count * count2
        print str(count) + " * " + str(count2) + " = " + str(result)
        if count2 == n:
            count += 1
            count2 = 1
        else:
            count2 += 1

这是一个期待的输出:

>>>print_multiplication_table(2)
new number: 2
1 * 1 = 1
1 * 2 = 2
2 * 1 = 2
2 * 2 = 4

>>>print_multiplication_table(3)
new number: 3
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9

在我添加while循环之前,一切正常:

while count != n and count2 != n:

现在我的输出看起来像这样:

>>>print_multiplication_table(2)
New number: 2
1 * 1 = 1
>>>print_multiplication_table(3)
New number: 3
1 * 1 = 1
1 * 2 = 2

我犯了什么错误,如何解决?

感谢。

3 个答案:

答案 0 :(得分:3)

在循环时将更改为:

while count <= n and count2 <= n:

答案 1 :(得分:2)

import itertools
def print_multiplication_table(n):
    nums = range(1,n+1)
    operands = itertools.product(nums,nums)
    for a,b in operands:
        print '%s * %s = %s' % (a,b,a*b)

print_multiplication_table(3)

给出:

1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9

range生成各个操作数; product生成笛卡尔积,%是将值替换为字符串的运算符。

n+1是范围如何工作的工件。请help(range)查看解释。

通常在python中,最好使用丰富的特征来构造序列以创建正确的序列,然后使用单个相对简单的循环来处理如此生成的数据。即使循环体需要复杂的处理,如果您先注意生成正确的序列,也会更简单。

我还要补充一点,while是错误的,有一个明确的迭代序列。


我希望通过推广上述代码来证明这是一种更好的方法。你很难用你的代码做到这一点:

import itertools
import operator
def print_multiplication_table(n,dimensions=2):
    operands = itertools.product(*((range(1,n+1),)*dimensions))
    template = ' * '.join(('%s',)*dimensions)+' = %s'
    for nums in operands:
        print template % (nums + (reduce(operator.mul,nums),))

(在此处:http://ideone.com/cYUSrL

您的代码需要为每个维度引入一个变量,这意味着要跟踪这些值的列表或字典(因为您无法动态创建变量),以及每个列表项的内部循环。

答案 2 :(得分:-1)

尝试

def mult_table(n):
    for outer_loop_idx in range(1,n+1):
        for inner_loop_idx in range(1,n+1):
            print("%s + %s = %s" % (outer_loop_idx,inner_loop_idx,outer_loop_idx*inner_loop_idx)

对于迭代工作的地方,你没有看到很多。 这段代码在编辑器窗口中看起来很棒......