# Break and Continue: While Loops

BartC bc at freeuk.com
Thu Jun 23 06:15:06 EDT 2016

```On 23/06/2016 05:17, Elizabeth Weiss wrote:
> CODE #1:

> i=0
> while True:
>    i=i+1
>   if i==2:
>      print("Skipping 2")
>      continue
>   if i==5:
>      print("Breaking")
>      break
>    print(i)
>
> ------
>
> Questions:
> 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?

i=0 doesn't mean that 'i' is equal to 0.

In Python, "=" means 'assignment'. Something more like this:

SET i to 0

i=i+1 means:

SET i to i+1

'i' is a name for some value. The value of 'i' can change, usually
through assignments. If 'i' currently has the value 37, then:

SET i to i+1

will now store i+1 (ie. 38) into 'i'. Repeating that will set 'i' to 39
and so on.

To test if 'i' has a certain value, then '==' is used (to distinguish it
from '=' which means SET).

So i==37 will give True if i currently has a value of 37, or False
otherwise. This is used in your code:

if i==2:
print ("Skipping 2")
continue

The indented lines are executed when i has the value 2.

> 1. what does the word True have to do with anything here?

The 'while' statement (like others such as 'if') takes an expression
that should give True or False. If True, the loop is executed once more.

Actually pretty much any expression can be used, because Python can
interpret almost anything as either True or False. Don't ask for the
rules because they can be complicated, but for example, zero is False,
and any other number is True. I think.

Anyway, your code is doing an endless loop. Python doesn't have a
dedicated statement for an endless loop, so you have to use 'while True'
or 'while 1'.

(Well, the loop is only endless until you do an explicit exit out of it,
such as using 'break'.)

--
Bartc
```