javapythonfor-loop

How do I implement the equivalent for-loop?


In java, I can have the following loop:

for(int i=1;i<=c;i++){
    for(int j=i; j<=C;j++){
        ecc...
    }
}

How do I write the equivalent loop in python?


Solution

  • Using for + range

    In python you can get a range by invoking range(begin, end) — where begin denotes the start of the range, and end is the upper limit (not included in the resulting range). Mathematically speaking the result will be the set of numbers in the range [begin, end).

    In order to port your code into , you can easily create an outer range with the construct previously mentioned, and then have the inner range depend on the former.

    for i in range (0, c+1):
      for j in range (i, C+1):
        ...
    

    Using while

    You can of course also write the equivalent looping construct using while, even though this is not very pythonic — nor is it as clean.

    i = 0
    while i <= c:
      j = i
      while j <= C:
        ...
        j += 1
      i += 1