While Loops: Christopher Harrison - Content Developer Susan Ibach - Technical Evangelist
While Loops: Christopher Harrison - Content Developer Susan Ibach - Technical Evangelist
for steps in range(20):
What if we don’t know how exactly how many times
to repeat an event
• Wash the dishes until they are all clean
• Keep guessing until you get the right answer
• Read all the values in a file or in a database
While Loops allow you to execute until a particular
condition is true
You have to declare the
variable before you use
answer = "0" it in the loop
answer = input("What is 2 +
2 ")
print ("Yes! 2 + 2 = 4")
Remember only the indented code
is repeated, so this command only
executes after you exit the loop
DEMO
While loop
Can you figure out what this code will do?
import turtle
counter = 0
while counter < 4:
turtle.forward(100)
turtle.right(90)
counter = counter+1
• Yes
While loops can be used instead of for loops
import turtle import turtle
for steps in range(4): counter = 0
turtle.forward(100) while counter < 4:
turtle.right(90) turtle.forward(100)
turtle.right(90)
counter = counter+1
import turtle
counter = 0
while counter <= 4:
turtle.forward(100)
turtle.right(90)
counter = counter+1
• It
How many lines will this loop draw?
import turtle
counter = 1
while counter < 4:
turtle.forward(100)
turtle.right(90)
counter = counter+1
• It
Click to edit Master
subtitle style
Looping issues
How many lines will this loop draw?
import turtle
counter = 0
while counter < 3:
turtle.forward(100)
turtle.right(90)
• You will encounter problems where a while loop is the only way
to solve a problem
•
Your challenge