Question: s mentioned in the video, a while loop is a mechanism to allow you to repeat set of steps many times as long as a

s 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 30 seconds. Then you check if its still too cold. Then put it in for another 30 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 30 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 boolean_condition:
# indented statements
# to execute when the condition is True
A while loop has
while boolean_condition:
# indented statements
# that will be executed
# as long as the condition is True
# a statement to potentially change the boolean_condition
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 =0 # count is the loop control variable
while count <5: # count <5 is the Boolean condition
print("Hello")
count = count +1 # the loop control variable is changed
Code Visualizer
TRY IT
What happens if you:
Change the while statement to while count <10:?
Change the last line of code to count = count +2?
Change the while statement to while count <0:?

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!