+ 3

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.

9th May 2018, 7:12 AM
Raghavendra Sharma
6 ответов
+ 10
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.
9th May 2018, 7:18 AM
Dev
Dev - avatar
+ 3
Thank You Dev, Got it Now, modified it & now works fine!!!
9th May 2018, 7:25 AM
Raghavendra Sharma
+ 3
Antoan Videnov Actually, your acting is not encouraged in Sololearn as it can lead to spam
10th May 2018, 2:14 AM
Muhd Khairul Amirin
Muhd Khairul Amirin - avatar
+ 2
Well, hi there! :) Just here to comment :)
9th May 2018, 12:23 PM
Antoan Videnov
Antoan Videnov - avatar
+ 1
thank you so much
17th May 2018, 5:31 AM
ANNM
ANNM - avatar
+ 1
yo man.. you challenged me really hard.. i like it 😂
18th Jun 2018, 8:25 AM
raj aryan
raj aryan - avatar