+ 1

Is there any particular pattern for arranging a while command having the conditional statement and incremental statement?

In previous lessons(1-3) under while statement, "print(i)" command seemed to work regardless of whether it was put before the incremental and conditional statements, in-between or after but in this case(4), my attempt to rearrange and see if it would still work failed. Any help please?

4th Jul 2017, 12:10 PM
Bueze
Bueze - avatar
4 Respostas
+ 2
I'm assuming that you are talking about this code here: i = 1 while i <= 5: print(i) i = i + 1 print("Finished") To answer your question in general, yes, there is a pattern and a reason for this order. The 'while' condition activates because i is less than 5, and therefore it is "True". Which means, the block of code that is indented under it will activate until the While condition is made False. You can rearrange the code if you want, but one, it won't have the same effect and if you keep the same condition in the while loop, it'll do what is called an 'infinite loop' and never stop. Two, keep in mind that the while condition needs at least 1 statement/code under it, otherwise you'll get angry red text (indentation error). It also does not matter if you place the i = i + 1 before or after the print(i) statement. The only change will be that the print function will print what the value of that variable is when it was called. I'm just speculating you're referring to this question since you mentioned while, and the variable i. (process of elimination). If I'm wrong, well Joker will make fun of me for it because he waited. lol
4th Jul 2017, 2:16 PM
Sapphire
0
Need to see the code to tell you why
4th Jul 2017, 1:07 PM
LordHill
LordHill - avatar
0
OK Sapphire. The last paragraph of your response answered my question. Thanks alot. Joker's taunts may have to wait for another day 😁
4th Jul 2017, 4:01 PM
Bueze
Bueze - avatar
0
Thanks too @joker
4th Jul 2017, 4:01 PM
Bueze
Bueze - avatar