For loop in python (or in general) | SoloLearn: Learn to code for FREE!

+1

For loop in python (or in general)

Can somebody explain me how does for loop work step by step in layman language with practicle example...? Thank u in advance

6/1/2020 3:35:47 PM

Munir Ahmed Yakin

8 Answers

New Answer

+8

Here is an explanation about for loops in python. https://code.sololearn.com/cu1c6tKg4ev1/?ref=app

+10

• Looping in Python — https://treyhunner.com/2016/04/how-to-loop-with-indexes-in-python/

+5

Munir Ahmed Yakin You summed it up nicely. To expand further, for loops are condensed while loops. The parts of a while loop are simply: 1. code block: executed in each loop 2. condition: loop again if true Generally speaking, any loop can repeatedly execute a "code block" multiple times as long as some conditional expression remains true. Now let see this with a while loop: ------ while(condition is true) run this block of code --- Expanded C style: ------ int i = 0; //initialize counter //condition: true until i is 10 while(i < 10) { i++; //increment by 1 //run code block } //10 times --- Converted to for loop: ------ for(initializer; condition; increment) run this block of code --- Expanded C style: ------ /* Combine parts from while loop: - initialize counter - condition: is true until 10 - increment by 1 */ for(int i = 0; i < 10; i++) { //run code block } //10 times --- See how these loops are essentially the same? while( ... ) {...} for( ; ... ; ) {...}

+3

So what I understand is : for loop will run its code x times x being number mentioned in range , am I rite?

+2

in python: for i in range(10): Print (i) result : the code will print the number from zero : 9 in separate lines

+2

in C++ int i; for(i=0; i<=10;i++){ print(i) } Result : the code will print the numbers from zero : 10 in separate lines

+2

Yes , the number of times is 10 but the loop start from 0:9 Munir Ahmed Yakin

+2

For loop is used to execute a block of code repeatedly, within the range that you have specified for i in range(19): print(i) It will print numbers from 0 to 18 NOTE:Identation mark : at the end of the loop declaration is very very important for i in range(5, 18): print(i) it will print numbers from 5 to 18 Note:If we want to print n numbers we have to specify range of n+1 for i in range(0, 13, 4) print(i) It will print 0 4 8 12 We can assign range here for i in range(starting,range,particular range you want):