0

Why doesn't it check a statement outside the while loop ?

For example the question I was given is : (((I=5 While true: Print (i) I=I-1 If I<=2 Break))) But why doesn't this just conclude that after the first loop I!=5 so the loop shouldn't continue??

8th Jan 2019, 9:41 AM
Rushan 1
5 Answers
+ 5
First of all, what programming language is that?
8th Jan 2019, 9:45 AM
Anna
Anna - avatar
+ 5
Doesn't look like any python version I know. Copy and paste this code: i = 5 while True: print(i) i = i - 1 if i <= 2: break into the textbox here: http://pythontutor.com/visualize.html#mode=edit and click on "visualize execution". On the next site, click on "forward" to see a step by step execution of the code.
8th Jan 2019, 9:49 AM
Anna
Anna - avatar
+ 2
Thanks
8th Jan 2019, 9:56 AM
Rushan 1
+ 2
I didn't see the last sentence of your question, so here's an addition: In this code: i = 5 while True: # do something "while True" doesn't check if i == 5. "while True" leads to an infinite loop that doesn't check for any condition. "while True" is actually a short form of "while True == True". True is always True so that loop will go on forever and ever. You could write something like "while 1 == 1" or "while 'hello' == 'hello'" as well. The condition is always True, so it creates an infinite loop. Whenever your loop doesn't check for a certain condition, it is very important to have a break condition within the loop. In your code, the break condition is "if i <= 2". If this condition is True, the loop will break.
8th Jan 2019, 12:18 PM
Anna
Anna - avatar
8th Jan 2019, 9:45 AM
Rushan 1