On for loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

On for loop

Pls I was tryingsomething like an experiment I tried this code For I in range(1,11): print(I) print(I,end=" ") And it resulted into this 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 Pls can anyone explaining how it turned out to be like this thanks

5th Sep 2022, 9:26 AM
Oyedeji Hiqmat
Oyedeji Hiqmat - avatar
3 Answers
+ 5
the first print statement prints number followed by '\n' -> newline character second print statement prints number followed by space . i will write _ for representing space and #number) to mention iteration number in loop #1) i is 1 so, 1 1_ is printed in #1) #2) i is 2 since previous line ended with _ 2 is printed on the same line so after #2) state of output is 1 1_2 2_ and this continues ...
5th Sep 2022, 9:47 AM
Prashanth Kumar
Prashanth Kumar - avatar
+ 2
Prashanth Kumar is right but let my explain it in another way: So the program has the numbers 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 and then in the for block it calls them all for the loop. The simple explanation of the loop is as follows: the first print prints the number i, then the second print prints the number i again on the next line and puts a space at the end. When it comes to the next number to be printed as i. The first print does not go to the next line, and after that space is created, it prints the number i, and again the second print prints the number i in the next line along with a space. The point is that the first print in loops does not go to the next line
5th Sep 2022, 10:57 AM
Ramtin Jafari
Ramtin Jafari - avatar
0
I hope that helped
5th Sep 2022, 10:57 AM
Ramtin Jafari
Ramtin Jafari - avatar