How to print i after running for loop twice?

Viewed 2767

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?

3 Answers

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)

First off there is no need for the inner loop to increment by a constant value. This does the same as your code above but in a clearer way:

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

This will print

101
102
103

To get your output, try using an auxiliary variable:

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

which will get your desired output

The code below works by unpacking all values within the range() by using the * operator.
Sidenote: The range() function has a step parameter, that specifies the incrementation.

print(*range(100, 300, 100))

The simpler version of the code above would be:

for i in range(100, 300, 100):
    print(i)

Output:

100 200
Related