如何在Python(3.0版)中创建嵌套循环?
我想尝试以下循环向我展示两个数字的产品:
def PrintProductsBelowNumber(number): number1 = 1 number2 = 1 while number1 <= number: while number2 <= number: print(number1, "*", number2, "=", number1 * number2) number2 += 1 number1 += 1 PrintProductsBelowNumber(2)
结果我得到:
1 * 1 = 1 1 * 2 = 2
所以看起来number1上的外部循环不会运行.
如何使number1循环运行,从而获得:
1 * 1 = 1 1 * 2 = 2 2 * 1 = 2 2 * 2 = 4
Adam Rosenfi.. 14
number2
只有初始化一次,你需要为内循环的每次迭代重新初始化它.但是,这段代码非常类似C而且不是非常Pythonic.更好的方法是使用for number in range(n)
构造:
def PrintProductsBelowNumber(number): for number1 in range(1, number+1): for number2 in range(1, number+1): print(number1, "*", number2, "=", number1 * number2)
Mike Boers.. 8
因为在内部循环第一次完成后,您没有将number2设置回1.number1然后递增,但由于number2仍然太高,内部循环不会再次运行.
def PrintProductsBelowNumber(number): number1 = 1 while number1 <= number: number2 = 1 while number2 <= number: print(number1, "*", number2, "=", number1 * number2) number2 += 1 number1 += 1 PrintProductsBelowNumber(2)
编辑:亚当的解决方案总的来说要好得多,但这是为了说明为什么你的工作方式不像你认为的那样.
number2
只有初始化一次,你需要为内循环的每次迭代重新初始化它.但是,这段代码非常类似C而且不是非常Pythonic.更好的方法是使用for number in range(n)
构造:
def PrintProductsBelowNumber(number): for number1 in range(1, number+1): for number2 in range(1, number+1): print(number1, "*", number2, "=", number1 * number2)
因为在内部循环第一次完成后,您没有将number2设置回1.number1然后递增,但由于number2仍然太高,内部循环不会再次运行.
def PrintProductsBelowNumber(number): number1 = 1 while number1 <= number: number2 = 1 while number2 <= number: print(number1, "*", number2, "=", number1 * number2) number2 += 1 number1 += 1 PrintProductsBelowNumber(2)
编辑:亚当的解决方案总的来说要好得多,但这是为了说明为什么你的工作方式不像你认为的那样.