the block of code continues to repeat as long as a condition is true
as soon as the condition evaluates to false, the loop ends
What is the while loop syntax? →
Great. So. Why Even?
Sales Commission Program
Starting Out with Python has a program that:
asks for a salesperson's number of sales and their rate
…and then calculates their sales commission.
Commission for 10, Please?
Is it possible to change the code in the previous slide so that the program requests data and calculates commissions for 10 salespersons … WITHOUT USING A WHILE LOOP? →
Of course! It's tedious, but just write the code 10 times!
What About Counting?
Can you write a program to count from 1 to 5 by printing out each number on a new line WITHOUT USING A LOOP (we saw this previously) →
Counting Without a While Loop
again, very tedious
there's a repeating pattern of code
…but it's totally possible!
Last Example for Motivating Loops, I Swear
Continue? (Yes/No)
WITHOUT USING A WHILE LOOP, is it possible to write a program that: →
asks a user if they want to continue
if they say yes, the program will ask them if they want to continue again
this goes on until they don't say Yes
Continue? (Yes/No)
We could try using consecutive nested if statements, but we don't know how deep the nesting could go.
Functions!?
There's actually a way to do this using a function definition that calls itself.
We'll take a look at recursion later this semester.
Loops Will Make All of Those Previous Programs Easier to Write!
Iteration and Loops
Some formal definitions:
iteration - repeated execution of a set of programming statements
loop (or a repetition structure) - the actual structure that allows repeated execution of a statement or a group of statements. The statements are repeated either:
a specific number of times or …
as long as a certain condition is true
Two Types of Loops
There are two broad categories of loops:
condition controlled - condition determines number of repetitions
count controlled - loop for a specific number of times
(it turns out that you can simulate count controlled loops in condition controlled loops)
guess which one a while loops is?
A while loop is a condition controlled loop.
While Loops
Condition Controlled Loops
a condition controlled loop causes a set of statements to be repeated as long as a condition is true
again, in Python, the while statement allows us to write a condition controlled loop
… or more succinctly: while a condition is true, do some stuff
a while loop consists of two parts:
a condition (a boolean expression) that is continually tested for a True or False value
a block of statements to repeat
While Loop Logic
A flow chart representing a while loop:
While Loop Logic Continued
What happens if the condition is True?
* one or more statements are executed
* condition is tested again
What happens if the condition is False?
The flow goes to the statements after the while loop
Compared to an If Statement
The flow chart for an if statement looks pretty similar to a while loop. What do you think the difference would be from the diagram showing while loop logic? →
If Statement Flow Chart
While Loop Syntax
A template:
Some real code:
What does this output? →
Basic While Loop Examples
Trivial Cases, Again
What do these snippets of code print out?→
Let's Step Through True
condition is true
print "I'm true!"
go back to top
condition is true
print "I'm true!"
go back to top
you know the deal
Let's Step Through False
condition is false
We never even get into the body of the loop!
Slightly More Complicated
What does this print out? →
Slightly More Complicated Continued
Let's add one line. What does this print out? →
Slightly More Complicated Continued Continued
Going through each iteration
condition (keep_on_going) is true
print "I'm going!"
set keep_on_going to false
condition (keep_on_going) is false
Loop ends after one iteration.
What Happened There?
we had some state outside of the loop
within the loop we mutated / changed that state to eventually get out of the condition
consequently, the loop terminates
sometimes we call these kinds of variables sentinel variables
they only let certain conditions in!
Affecting the Outcome of the Condition
To change the outcome of your conditional:
maintain state
declare a variable outside of the loop!
mutate that state on loop iteration
change that variable inside the loop!
this will eventually cause the conditional to fail
examples:
using operators to change a variable in your condition
using input to change a variable in your condition
Some Practical While Loop Examples
Handling Input, Continue Again
First an easy one. Let's go back to the continue program that we discussed earlier:
ask a user if they want to continue
if they say yes, the program will ask them if they want to continue again
this goes on until they don't say Yes
Continue Program, Some Questions
what are we repeating?
how long are we repeating it, or what's the condition to keep on repeating it?
is there any data that we're keeping track of?
Continue Program Implementation
Notice that, like an if statement, variables declared outside of the body of the while loop can be accessed (and even changed) within the body of the while loop.
Another Continue Program Implementation
in order to go into the while loop, just start off with something that makes the condition true!
what are some benefits to using this pattern? →
we consolidate the request for input into a single point in the program
if we want to change the question, just one place
(note that not all programs can fit this pattern)
A More Flexible Continue
Let's modify the previous program slightly so that it accepts either yes or yeah.
ask a user if they want to continue
if they say yes or yeah, the program will ask them if they want to continue again
this goes on until they do not say Yes or Yeah
Flexible Continue Program, Some Questions
what are we repeating?
how long are we repeating it, or what's the condition to keep on repeating it?
is there any data that we're keeping track of?
Flexible Continue Program, Implementation
To implement this, modify the condition appropriately by adding or answer == 'Yeah'
Designing How Your While Loop Works
So, I Heard You Want to Repeat Some Code…
If you have some code that requires repetition, what questions should you ask?
first, will this require a while loop?
as long as there's repeated code that's based on a condition, yes!
what's the condition … which will probably lead to….
what data is in the program?
what should the data initially be set to, if anything at all?
how will the loop terminate?
We've Seen These Before… Some More Examples
Odd Numbers Except 13
Write a program that… →
prints all of the odd numbers from 1-99
skips 13
There are a few ways to do this! What are some general strategies for solving this problem?→
Write a program that continually asks the user for numbers, and asks them if they'd like to keep going. In the end, it should output the average of all of the numbers entered→
Some Hints, Please?
Let's try keeping track of multiple variables:
a user's answer to whether or not the program should continue
(possibly) the number that the user has just entered
the total (sum) of the numbers that a user has entered
the count of numbers input
An Average Solution
Syntactic Sugar
Increment / Decrement
We've used the following syntax to increment or decrement a variable
Slightly tedious…
Increment / Decrement Continued
There's some syntactic sugar that makes doing this less verbose: use += or -=
n += 1 is the same as n = n + 1
n -= 1 is the same as n = n - 1
More Syntactic Sugar
This works for other operators too. What does this code print out? →
What About Strings?
Also works with strings…. What does this code print out? →
Some More Exercises!
Powers of Two
Continually print out the next power of two, only if you say 'y' →
Squares
Continually ask for a number, print out the square, and ask to continue →
Other Exercises
count the number of digits in an int
repeatedly use integer division
…until the original number becomes 0
keep count of divisions
continually add exclamation points to a word
ask for a word
ask for x number of exclamation points
print out resulting word and exclamation points
continue asking for another word and exclamation points