Economister
Economister

Reputation: 67

Why does this code not produce a square 2d-array? What makes it become triangular?

I'm trying to print a square two-dimensional array of 0s. I don't understand why I keep getting a triangular shape with this code. Why is it that with each ROW I print, I print one less column?

def ar(i):
    j = i
    for i in range(i):
        for j in range(j):
            print('0', end=" ")
        print()

Upvotes: -1

Views: 39

Answers (1)

Patrick Artner
Patrick Artner

Reputation: 51643

range(5) will produce the values from 0 to 4 - one less then the inputted number.

i = 5
j = i   # this is overwritten by the loop-j
for _ in range(i):       # on the first i
    for j in range(j):       # j will get 4 at max, so for the next i your j 
        print('0', end=" ")  # only produce a range(4), then (3) ... hence: triangular
    print()

Your inner loop j overwrites your local j and due to the nature of range() it will decrease by 1 for each outer loop.

Fix:

You do not need named loop-vars, substitute with _:

def ar(i):
    for _ in range(i):
        for _ in range(i): # no j needed at all
            print('0', end=" ")
        print()

ar(5)

Output:

0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0

Upvotes: 1

Related Questions