Search code examples
pythonfor-looprangenested-loops

How to print i after running for loop twice?


I'm trying to print out the value of i every time the inner loop finishes iterating.
i can be 10, 20, 200, 2000, or any number really, but for this instance I chose 100.

for i in range(1, 3):
    for ii in range(1, 100):
        i += 1
    print(i)
print(i + i)

Given Output:

100
101

Wanted Output:

100
200

How can I get the wanted output?


Solution

  • Your outer loop variable is also named i. Since you're overloading that variable name, it gets reset every time.

    Consider instead using the common idiom for _ in range(n) which will execute its contents n times.

    x = 0
    for _ in range(3):
        for _ in range(100):
            x += 1
        print(x)
    

    although as solid.py rightly points out in the comments on the question, for this specific use case it's probably easier to not add 1 over and over again, and instead just use math or a more appropriate range.

    for i in range(1, 3):
        print(i * 100)
    
    # or
    
    for i in range(100, 301, 100):
        print(i)