How to make nested for-loop's number greater than or equal to previous for-loop's number

55 views Asked by At

How can I make it so that the right number is always greater than or equal to the left number?

for i in range(5):
  for j in range(5):
    # Right (j) should be greater than or equal to left (i)
    # i.e. j >= i should always be True
    print(i, j)

I tried to use: if i > j: but I did not know how to continue it.

2

There are 2 answers

0
cards On BEST ANSWER

There are 2 basics errors:

  1. the condition i > j stands for i strict smaller than j. To include equality use the relation i >= j

  2. left, right and i, j are swapped: left should be i, right j

Then use the condition in the innermost body of the loops

for i in range(5):
    for j in range(5):
        if j >= i:
            print(i, j)

Remark: you could use also the dual relation i <= j

0
W D On

As mentioned by Andrej in the comments, you can change the second for-loop to for j in range(i, 5) - as shown below:

# Right will not be smaller than left
if __name__ == '__main__':
  for i in range(5):
    for j in range(i, 5):
      print(i, j)