While Loop Exection | Sololearn: Learn to code for FREE!


While Loop Exection

Need some clarification on why my code is behaving differently compared to the code copied, as both are same, only the string declared is different. Please see below for more update on the query. My code was i = 1 while i <=5: print(i) i = i + 1 print("Done:-0") When run, this gives me the output as follows: 1 Done:-0 2 Done:-0 3 Done:-0 4 Done:-0 5 Done:-0 When I copied the code from the lesson of while loops, the code looks like this. i = 1 while i <=5: print(i) i = i + 1 print("Finished!") The output for the above code is as follows: 1 2 3 4 5 Finished! Note: The code is all similar, but in the last statement instead of print("Finished!") I gave it as print("Done:-0") other than that, there is no significant difference. Would sincerely appreciate anyone helping me understand the logic behind two different outputs.

5/9/2018 7:12:17 AM

Raghavendra Sharma

6 Answers

New Answer


Indentation is the key to understand it. The print statement in the first case is indented and is inside the loop body so it is executed 5 times. The print statement in the latter case is not indented, thus is outside the loop body. Therefore it gets executed only once, when the loop finishes executing. Indentation = 4 whitespaces or a tab.


Thank You Dev, Got it Now, modified it & now works fine!!!


Antoan Videnov Actually, your acting is not encouraged in Sololearn as it can lead to spam


Well, hi there! :) Just here to comment :)


thank you so much


yo man.. you challenged me really hard.. i like it 😂