[Tutor] While loop

Dave Angel davea at davea.name
Sun Apr 7 06:09:42 CEST 2013


On 04/06/2013 11:23 PM, Najam Us Saqib wrote:
> Hi,
>
> Would you please help me by explaining that why " 5 " is skipped and not printed in the following program?
>

Seems to me the comments say it pretty well.  The continue statement 
causes execution to continue at the while statement, which has the 
effect of skipping the print.  Like Monopoly:  go directly to jail, do 
not pass go.


> Thank you.
> Najam.
>
> count = 0
> while True:
>      count += 1
>      # end loop if count is greater than 10
>      if count > 10:
>          break # means "break out of the loop"
>      # skip 5
>      if count == 5:
>          continue # means "Jump back to the top of the looop"
>      print count
>
> raw_input("\n\nPress the enter key to exit.")
>
> Output:
>
> 1
> 2
> 3
> 4
> 6
> 7
> 8
> 9
> 10
>
>
> Press the enter key to exit.

Incidentally, this looks like a transliteration of something written for 
some other language.  An experienced Python programmer would never write 
it this way.

I'd use something like (untested):

for count in xrange(11):
     if count != 5:
         print count

On the other hand, a course --teaching a C programmer to use Python-- 
might well use this as an early example, showing you later how much 
elegantly it can be done.


-- 
DaveA


More information about the Tutor mailing list