Break and Continue: While Loops
alister
alister.ware at ntlworld.com
Thu Jun 23 05:53:00 EDT 2016
On Wed, 22 Jun 2016 21:17:03 -0700, Elizabeth Weiss wrote:
> CODE #1:
>
> i=0 while 1==1:
> print(i)
> i=i+1 if i>=5:
> print("Breaking") break
>
> ------
> I understand that i=0 and i will only be printed if 1=1 The results of
> this is 0
> 1
> 2
> 3
> 4
> Breaking
>
> Why is Breaking going to be printed if i only goes up to 4? It does say
> if i>=5? Shouldn't this mean that the results should be:
> 0
> 1
> 2
> 3
> 4
> 5
>
> CODE #2:
>
> i=0 while True:
> i=i+1
> if i==2:
> print("Skipping 2")
> continue
> if i==5:
> print("Breaking") break
> print(i)
>
> ------
>
> Questions:
> 1. what does the word True have to do with anything here?
> 2. i=i+1- I never understand this. Why isn't it i=i+2?
> 3. Do the results not include 2 of 5 because we wrote if i==2 and if
> i==5?
> 4. How is i equal to 2 or 5 if i=0?
>
> Thanks for all of your help!
unrelated to your question
while 1==1
Don't do this.
code 2 you correctly use while True
to see the problem with your code
try following it through line by line with a pen & paper
writing the value for I each time it is changed.
(this is known in the trade as a "Dry Run")
--
Fame is a vapor; popularity an accident; the only earthly certainty is
oblivion.
-- Mark Twain
More information about the Python-list
mailing list