Question: As mentioned in the video, a while loop is a mechanism to allow you to repeat set of steps many times as long as a
As mentioned in the video, a while loop is a mechanism to allow you to repeat set of steps many times as long as a certain condition is true. For example, you may want to heat up leftover pizza in the microwave as long as its too cold. The pizza starts out too cold. So you put it in the microwave for seconds. Then you check if its still too cold. Then put it in for another seconds. Check if its still too cold. Repeat this process until it is warm enough the cheese is melted
The procedure, written in a Python like pseudocode would look like this:
temp get temperature of pizza
while temp is too cold:
heat in microwave for seconds
temp get new temperature of pizza
All while loops have these three elements:
an initial condition, usually involving initialization of a loop control variable. temp in this case
a Boolean condition that is tested each time through the loop to determine whether the loop body the statements indented under the while statement will be run or not. temp is too cold is a True or False statement that is our Boolean condition.
a statement at the bottom of the loop that will potentially change the loop control variable temp get new temperature of pizza.
Like branching statements, while loops are code blocks using indentation. An if statement has
if booleancondition:
# indented statements
# to execute when the condition is True
A while loop has
while booleancondition:
# indented statements
# that will be executed
# as long as the condition is True
# a statement to potentially change the booleancondition
While Loop Syntax
While loops use a : after the condition and indent for all commands that should be repeated when the condition is true. Here is a while loops that prints Hello five times.
count # count is the loop control variable
while count : # count is the Boolean condition
printHello
count count # the loop control variable is changed
Code Visualizer
TRY IT
What happens if you:
Change the while statement to while count :
Change the last line of code to count count
Change the while statement to while count :
TRY IT
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
