0

Why is 3 printed in this while loop?

If i = i-1, why does it include 3? If i = 3, then i-2 should start at 2, in my understanding. I'm a newbie at coding and computer languages. Less than 2 months type of newbie. :) i = 3 while i>=0: print(i) i = i - 1

25th May 2021, 10:29 PM
Julio Moreno
Julio Moreno - avatar
8 odpowiedzi
+ 3
If you want to start it at 2, print after you decrease by 1 i = 3 while i>=0: i = i - 1 print(i) 🙂
25th May 2021, 11:43 PM
David Ashton
David Ashton - avatar
+ 2
David Ashton :D yes, but so you will end at minus one instead of zero (the number of iterations/outputs will not be changed)... unless you change too the 'greater or equals' to 'strictly greater' ;P
25th May 2021, 11:49 PM
visph
visph - avatar
+ 2
@David Ashton @visph I see both points and this is where my thinking was heading, though I was confused about the coding equation. Visph, your last response was exactly what I was thinking... regarding the negative one. Your nuanced response brought yet another element to this. Thank you, David, for showing how the print function placement changes the output. So, what I learned from this discussion: position of the print() function matters--a lot! Thank for guys for helping me out! Now I feel less isolated in this learning process! Best, J.
26th May 2021, 12:29 AM
Julio Moreno
Julio Moreno - avatar
+ 1
because: i = 3 # assign 3 to i while i>=0: # 3 >= 0 is True so, enter loop print(i) # output i (3) i = i - 1 # now i = 3 - 1 = 2 why did you think that i = i - 1 would occur before outputing initial value of i?
25th May 2021, 10:39 PM
visph
visph - avatar
+ 1
@visph Thank you for the clarifying question! Now I get it. So a while loop included the original value, instead of only outputting the i = i - 1 results. This is the first time I post a question here. I really appreciate you taking the time to answer it so well! Best, J.
25th May 2021, 10:49 PM
Julio Moreno
Julio Moreno - avatar
+ 1
all that is indented below the while (or any other -- ie: if, else, try...) statement, belong to this statement (code block) and are executed linearly, from top to bottom ;)
25th May 2021, 10:53 PM
visph
visph - avatar
+ 1
i starts with a value of 3, inside the loop this value is printed, and the next line decrease the value of i by 1, so until next loop i=2.
27th May 2021, 2:43 AM
Andres Guzman
Andres Guzman - avatar
0
Julio Moreno what is best, J?
26th May 2021, 1:04 AM
Hëllo Wörld🔰
Hëllo Wörld🔰 - avatar