Break and Continue: While Loops

Elizabeth Weiss cake240 at gmail.com
Sun Jun 26 15:09:28 EDT 2016


On Thursday, June 23, 2016 at 1:20:37 AM UTC-4, DFS wrote:
> On 6/23/2016 12:17 AM, 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:
> 
> i is incremented up to 5, but you're printing i before incrementing and 
> evaluating it.
> 
> Move i=i+1 to the end and try it again.
> 
> 
> 
> 
> 
> > 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?
> 
> 'True' is the expression that's evaluated on each iteration of the While 
> loop.
> 
> while True:
>     print('True')
> 
> while 1:
>     print('True')
> 
> while 1==1:
>     print('True')
> 
> are all equivalent, and will run indefinitely, because the statements 
> after the while expression do nothing to stop the loop.
> 
> 
> 
> 
> > 2. i=i+1- I never understand this. Why isn't it i=i+2?
> 
> i=i+1 adds 1 to the current value of i, then assigns that value to i.
> 
> You can increment i by whatever you want:
> i=i+1
> i=i+2
> i=i+35
> etc.
> 
> 
> 
> 
> > 3. Do the results not include 2 of 5 because we wrote if i==2 and if i==5?
> 
> The print results don't include 2 or 5 because you said 'continue' if 2 
> and 'break' if 5.  So you skipped over 2, and exited at 5.
> 
> 
> 
> 
> > 4. How is i equal to 2 or 5 if i=0?
> 
> i=0 before you entered the While loop.  Then you increment it by one 
> (i=i+1) on each iteration of the loop.
> 
> 
> 
> > Thanks for all of your help!
> 
> 
> Also, there's a million python resources on the web.
> 
> http://www.pythonschool.net/basics/while-loops/

Got it! Thank you!



More information about the Python-list mailing list