By Mohammed Tanveer Mohsin via Discussions on Python.org at 07Jun2022 19:34:
I want to understand the execution of both program-1 and program-2.
In program-1, I can see the result it is breaking once the value reached 2.
Actually, it is spinning. I suspect you will find that program-1 never
finishes.
Thank you for including both the code and the resulting output.
While in Program-2, it is resulting values up to 10 by skip 3.
I’ve not understood the behavior of program-1 actually. Why it is not continuing up to 10.
Let’s look at program-1.
BTW, see the other comment to this post: it helps to surround your
Python code with triple backticks like this:
```python
your python code here
```
which will preserved the indenting in the forum.
Anyway, to your code:
i = 0
while (i<=10):
if (i==3):
continue
print(i)
i=i+1
If you put a print("top of loop")
right under the while
the
behaviour may be more obvious. When i==3
it continues directly to the
next iteration of the loop. Importantly, it does not run the i=i+1
code which increments the value in i
. So i
remains ==3
on the next
tieration, and so on forever.
Usually we would write such a “counting” loop like this instead:
for i in range(0, 11): # counts 0 through 10, stops before 11
if i != 3:
print(i)
By using a for-loop with a range()
the loop handles the increment
itself, and has no possibility of not incrementing. So your control
flow bug, where you accidentally avoided the increment, is outright not
possible.
Also, notice that instead of using continue
to skip the rest of the
loop body, we instead invert the test, and use the if-statement to skip
just the part of the loop body which we want to not happen. Control then
proceeds to the rest of the loop body so that the normal things happen.
Here, that body is empty below the if-statemment, but in your original
while loop, modified the same way:
i = 0
while (i<=10):
if (i!=3):
print(i)
i=i+1
you would not have skipped the increment.
A few other remarks:
- you do not need the brackets around the conditions, though they do no
harm
- you can write the increment like this:
i += 1
; again, what you wrote
is still valid, this is just a more readable alternative
Cheers,
Cameron Simpson cs@cskk.id.au