Break and Continue: While Loops
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Thu Jun 23 04:28:13 EDT 2016
On Thursday 23 June 2016 14:17, Elizabeth Weiss wrote:
> 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?
Consider:
"while the pasta is too hard to eat, keep boiling it"
"while you are feeling sick, stay in bed and drink plenty of fluids"
"While" repeatedly takes a condition, decides if it is true or false, and then
decides what to do. If you give it a condition True, that's *always* true, so
it repeats forever unless you use "break" to escape from the loop.
> 2. i=i+1- I never understand this. Why isn't it i=i+2?
i = i + 1 increase i by one each time around the loop:
i = 0, then 1, then 2, then 3, then 4...
If you used i = i+2, it would increase by two each time around the loop:
i = 0, then 2, then 4, then 6, then ...
> 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?
i starts off as 0. But then you increase it by 1 each time around the loop.
Can I ask, have you learned about for loops yet? There seems to be a fashion
among some teachers and educators to teach while loops before for loops. I
think that is a terrible idea, while loops are so much more complicated than
for loops.
Try this example instead:
for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
if i == 2:
print("skipping")
continue
if i == 5:
print("breaking")
break
print("i =", i)
The main thing you need to know to understand this is that the line "for i in
..." sets i=0, then runs the indented block under it, then sets i=1 and runs
the indented block, then sets i=2, and so forth. Run the code and see if it
makes sense to you. Feel free to ask as many questions as you like!
The line "for i in [0, 1, 2, ..." is a bit wordy and verbose. Can you imagine
if you wanted to loop 1000 times? Fortunately Python has an abbreviated
version:
for i in range(10):
if i == 2:
print("skipping")
continue
if i == 5:
print("breaking")
break
print("i =", i)
--
Steve
More information about the Python-list
mailing list