+ 10

How Nested for loop worked

r=0 for x in range(10): for y in range(5): r+=1 print(r) What's the output??? And how ????

21st Oct 2021, 3:35 AM
Vaibhav
Vaibhav - avatar
2 Respuestas
+ 4
the output is 50 My reason is because 10 x 5 = 50 Lets think about how a for loop behaves. a for loop needs to finish all the set of instructions inside it to finish a iteration. therefore the program will execute and perform the the x for loop. once it performs the x for loop it needs to finish the 5 iterations of the y for loop to finish one iteration of the x for loop. another example of nested for loop r=0; for x in range(10): for y in range(5): for z in range(20): r+=1; print(r); the answer here is 1000 because 10 x 5 x 20 = 1000.
21st Oct 2021, 3:54 AM
Danielle Bagaforo Meer
Danielle Bagaforo Meer - avatar
+ 1
your outer loop execute 10 time and inside loop will execute total 5 time r+=1 will work as a counter if your outer loop work one times then inside loop will work 5 times like this initial outer loop x=0 Jump to inside y=0 this inside loop will execute 5 time first time r+=1=1 then again y=1 r+=1 means r=1+1 again y will increase by 1 so y=2 r=2+1 Same for y=3 r=3+1 ..... when y will be 5 here condition false and outer loop will be execute at this time x will will be increase by one initial it was 0 . Now 1 again inside loop work 5 time When x =2 again inside loop work 5 time x=3. Again 5 times ..... When x=10 here condition false
21st Oct 2021, 3:59 AM
A S Raghuvanshi
A S Raghuvanshi - avatar