graph TD A[Before] --> B{Condition} B -- True --> C[Statements] C --> B B -- False --> D[After]
Write a turtle program that draws a 5-pointed star. Use a loop.
Turtle template code:
Write a turtle program that draws a 5-pointed star. Loop over the following list of colors for the sides: ['red', 'green', 'purple', 'blue', 'yellow']
Write a turtle program that draws 50 5-pointed stars at random positions on the screen.
Use the following code to get positions:
Tip
Add pen.speed('fastest')
before your loop to speed up the drawing.
distance
at 0.distance
distance
by 2Refinement: Instead of “Do the following 500 times”, do the following as long as pen.distance(0, 0)
is less than 500.
length
at 0.pen.distance(0, 0)
is less than 500:
length
length
by 1Example: colors = [‘red’, ‘black’, ‘blue’]
while
loopswhile
loopsA while loop executes a statement based on a boolean condition.
graph TD A[Before] --> B{Condition} B -- True --> C[Statements] C --> B B -- False --> D[After]
Analogy: while there are dishes in the sink, wash another dish.
What will this output?
To get out of this infinite loop, press Ctrl+C
in the Shell, or press the stop button in the toolbar.
In an otherwise infinite loop, use break
to exit:
while True:
statemets
if condition:
break
more_statements
Either of the statements blocks may be empty.
Before:
After:
How would you convert this to a mid-loop test?
for
loopsfor
loopsA Python for
loop iterates over a sequence of values:
str
: each characterlist
, tuple
, set
: each elementrange
: each numberdict
: each keynew_s
is a copy of s
new_s
is the reverse of s
new_s
is the final character of s
new_s
is the first character of s
s = input("Please enter a string: ")
new_s = ''
for char in s:
if char != ' ':
new_s = new_s + char
print(new_s)
new_s
is a copy of s
new_s
is the spaces of s
new_s
is s
with no spacesnew_s
is s
with spaces between every characterrange
functionrange
functionstart
: first numberstop
: up to but not including (“stop before”)step
: incrementOften used with for
loops.
idx
take?for idx in range(7):
for idx in range(1, 7):
for idx in range(0, 7, 2):
for idx in range(13, 10, -1):
By value:
By index:
Convert this code to use a for
loop: