Home python Explain to me nested loops in python

Explain to me nested loops in python

Author

Date

Category

the result:

0 0
0 1.
0 2
ten
eleven
12
twenty
2 1.
2 2.

Explain to me how it works is the code straight into the details and ask simple words!


Answer 1, Authority 100%

for – cycle. The same actions it carried out on the condition specified in parentheses. In this case, the figure in brackets 3 . This means that the loop will be executed three times, each time assigning variable specified after for , the value specified by the hypothesis.


In a series of for i in range (3) The default condition means that the variable i will be set on the 0 to 3 (but not including) . Thus, the variable i will take values: 0 , 1 , 2

.


However, there is a nested loop for the variable j . There nesting means that with one embodiment of the main loop, nested be executed 3 times. That is, until the i is equal to 0 , the variable j will have time to take the value 0 , 1 and 2 . Then displays the value i and the resulting values ​​of j .

So goes the first round of the cycle for the variable i . Since all of 3 and a nested loop also performed 3 times – the screen will appear (3 ∙ 3) = 9 rows where i receives 0 , 1 and 2 once, and j three times.


Answer 2, Authority 50%

First of all explain that the range (x) function returns an object “range”, if this function is fed one argument, then this object will look like: 0, 1, 2, 3, …, x – 1, respectively, i and j variables are counters for loops, which in turn take values ​​from 0 to 2.

  1. The outer loop begins execution of his body and the counter i = 0, in the body of the loop contains another loop with counter j, which will also take values ​​from 0 to 2.
  2. begins the launch of the inner loop and j = 0. 3. In the body of the internal
    cycle outputted current values ​​of the counter variable.
    The outer loop goes to the next iteration, only when
    fully process the inner loop, t. e. not yet become equal to j
    2, then i = 1 and the inner loop again, starting from 0 to 2, and outputs
    the values ​​of these counters

Answer 3

Oh, I do not know, but I will try, in the first for i = 0, and goes beyond the cycle, which meets the other for, and which will be carried out, where the condition j variable will be 0 1 2 respectively will indicate 0 0 0 1 0 2. After that, the main loop for nothing should he is repeated with variable i = 1, where again have further perform another cycle for a variable j equal to 0 1, 2 and displayed 1 0, 1 1, Feb. 1 etc.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions