Search code examples
pythonfor-loopnested-for-loop

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


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.


Solution

  • 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