简体   繁体   中英

What is wrong with my nested loops in Python?

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

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)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM