rows = range(1, 3) # range(1, 3)--> 1, 2 cols = range(1, 4) # range(1, 4) --> 1, 2, 3 for row in rows: for col in cols: print(row, col) # --- > 1 1 1 2 1 3 2 1 2 2 2 3 

It is not clear here, why in the second column 1, 2? We take that row row index, col column index, range(1, 3) range (1, 4) - number of rows and columns.

  • 0 pass: temporary variable row takes from rows (1, 2) - 1, then 0 iteration col takes temporary variable from cols (1, 2, 3) - 1.

  • 1 pass: temporary variable row takes from rows (1, 2) - 2?

And why in the end 6 columns? If you take each cycle of them separately, 5 is obtained, if only the 6th is 0 pass (iteration).

And another question is if i (nothing is assigned to the temporary variable before the loop), by default it always starts with 0 and starts iterating?

    1 answer 1

     rows = range(1, 3) # range(1, 3)--> 1, 2 cols = range(1, 4) # range(1, 4) --> 1, 2, 3 

    The first iteration takes the number 1 from rows and passes on. There is another cycle there and this cycle will not end until it passes through all three cols: 1-1, 1-2, 1-3 . Only after that you again rise to the level above and take the following value of rows equal to 2 and again three nested iterations of cols: 2-1, 2-2, 2-3 . Total is obtained two times in three, a total of six passes.

    Your mistake is that you rise to a higher level in your judgments before all the operations inside the cycle have been completed. And inside you have three mandatory pass.


    Even if you assign something to the variable i iterations will still start from scratch. The cycle for val in iter means to take the next element from iter and place it in val , only then we go down to the body. And so on until all the elements that you need to go to iter run out. Therefore, even if you assign something to i , it will be erased, because The main sequence here is in the iter itself.