Reputation: 4587
How do I make nested loops in Python (version 3.0)?
I am trying to get the following loops to show me the products of two numbers:
def PrintProductsBelowNumber(number):
number1 = 1
number2 = 1
while number1 <= number:
while number2 <= number:
print(number1, "*", number2, "=", number1 * number2)
number2 += 1
number1 += 1
PrintProductsBelowNumber(2)
As a result I get:
1 * 1 = 1
1 * 2 = 2
So it seems the outer loop over number1 does not run.
How do I get the loop over number1 to run, and thus obtain:
1 * 1 = 1
1 * 2 = 2
2 * 1 = 2
2 * 2 = 4
Upvotes: 0
Views: 8822
Reputation: 3288
You could modify Adam's solution with a list comprehension:
def PrintProductsBelowNumber(number):
results = [(i, j, i * j) for i in range(1, number + 1)
for j in range(1, number + 1)]
for number1, number2, result in results:
print(number1, "*", number2, "=", result)
or some variation thereof.
Upvotes: 0
Reputation: 6745
Because you aren't setting number2 back to 1 after the inner loop completes the first time. number1 then increments, but since number2 is still too high the inner loop doesn't run again.
def PrintProductsBelowNumber(number):
number1 = 1
while number1 <= number:
number2 = 1
while number2 <= number:
print(number1, "*", number2, "=", number1 * number2)
number2 += 1
number1 += 1
PrintProductsBelowNumber(2)
EDIT: Adam's solution is much better in general, but this is to show why your's wasn't working the way you thought it should in the first place.
Upvotes: 8
Reputation: 400592
number2
only gets initialized once, you need to re-initialize it for each iteration of the inner loop. However, this code is very C-like and not very Pythonic. The better way to do it would be to use the for number in range(n)
construct:
def PrintProductsBelowNumber(number):
for number1 in range(1, number+1):
for number2 in range(1, number+1):
print(number1, "*", number2, "=", number1 * number2)
Upvotes: 14