10.2. Introducing the While Loop¶
Recall that a for
loop is designed to repeat steps for every value in a list. The range
function in the code below is designed to generate a list that looks like [0, 1, 2, 3, 4] and
thus causes the loop to repeat 5 times. By forcing us to provide that list of values, the for
loop requires us to specify the number of iterations there will be before we begin looping.
for iteration in range(5):
guess = 1/2 * ((number / guess) + guess)
However, there is another way to repeat statements: the while
loop. It will repeat the
body of the loop as long as some logical expression is true. Just like with a for loop,
the body of a while loop is the lines of code after while
that are indented. A logical
expression is one that is either true or false like x < 5
. (We will talk more about them
later.)
While
loops are typically used when you don’t know how many times to execute the loop. they
allow us to say “keep repeating this while we don’t have an answer”. One reason we might not
know in advance how many times to repeat is if we are getting input from outside the program.
The code below will keep asking you to enter numbers. It will do so until you enter a number
that isn’t negative. It will print out the sum and average of all of the numbers you have entered.
The loop in this sample takes your input, which is stored in value
as a string like “12”, and
turns that into an integer like 12. It checks to see if that value is greater than 0. If so, it
does the loop body, if not, we skip over the loop body and continue with the rest of the program.
- 3
- All the statements that are indented 4 spaces to the right of the
while
are part of the body of the loop. - 4
- There are four statements that are indented 4 spaces to the right of the
while
statement, so there are four statements in the body of this loop. - 5
- Is the
print(message)
line indented 4 spaces to the right of thewhile
? If not it is not part of the body of the loop. - 6
- While line 11 is indented this is just to allow the print statement to take up more than one line. The print statement is not indented so the body of the loop contains just 4 lines.
How many lines are in the body of the while
loop in while_input above?
- It prints the sum is 0 and the average is 0.
- Do you see code to do this in the program?
- It prints a message that it can't divide by 0.
- This might be nice, but is that what happens?
- There is an error.
- You will get a ZeroDivisionError since you can't divide by zero.
What happens if you enter a negative number as the first input to the code above?