For loop in python (or in general) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

1st Jun 2020, 3:35 PM
Munir Ahmed Yakin
8 Answers
+ 8
Here is an explanation about for loops in python. https://code.sololearn.com/cu1c6tKg4ev1/?ref=app
1st Jun 2020, 3:57 PM
Lothar
Lothar - avatar
1st Jun 2020, 5:24 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 6
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( ; ... ; ) {...}
1st Jun 2020, 4:48 PM
David Carroll
David Carroll - avatar
+ 3
So what I understand is : for loop will run its code x times x being number mentioned in range , am I rite?
1st Jun 2020, 3:45 PM
Munir Ahmed Yakin
+ 3
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):
2nd Jun 2020, 3:00 AM
VAMSI
VAMSI - avatar
+ 2
in python: for i in range(10): Print (i) result : the code will print the number from zero : 9 in separate lines
1st Jun 2020, 3:40 PM
Muhammad Galhoum
Muhammad Galhoum - avatar
+ 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
1st Jun 2020, 3:42 PM
Muhammad Galhoum
Muhammad Galhoum - avatar
+ 2
Yes , the number of times is 10 but the loop start from 0:9 Munir Ahmed Yakin
1st Jun 2020, 4:11 PM
Muhammad Galhoum
Muhammad Galhoum - avatar