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
9 Answers
+ 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)
đ
+ 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
+ 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.
+ 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?
+ 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.
+ 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 ;)
+ 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.
0
Julio Moreno what is best, J?