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??
5 odpowiedzi
+ 5
First of all, what programming language is that?
+ 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.
+ 2
Thanks
+ 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.