+ 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?
4 Réponses
+ 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
0
Need to see the code to tell you why
0
OK Sapphire. The last paragraph of your response answered my question. Thanks alot.
Joker's taunts may have to wait for another day 😁
0
Thanks too @joker