এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
Primary & Middle School Computer Science · শ্রেণি 1–9
16Repeating with for: Turtle Drawings
Leo has written a program that draws a square: two lines, “go forward” and “turn left”, written four times. Now he wants a shape with 36 sides, almost a circle. That would be 72 lines, all the same, and one typing mistake would spoil the shape. There must be a better way: a computer is very good at doing the same thing again and again, if we tell it how many times.
You already know
An algorithm can say “repeat 4 times” instead of writing the same steps four times (Chapter 10). A variable is a name for a value, and an assignment such as n = 6 gives it a value (Chapter 15).
16.1 The turtle
Definition 16.1 (Turtle graphics)
Turtle graphics is a way of drawing with a program: a pen, called the turtle, moves on the screen and leaves a line behind it. It has a position and a heading, the direction it faces, and it obeys forward(d) (move steps straight ahead), left(a) and right(a) (turn on the spot by degrees), penup() and pendown() (lift or lower the pen).
The turtle starts in the middle of the window, facing right. Python’s turtle module brings these instructions; a program first takes the ones it needs with from turtle import .... Its last line, done(), keeps the window open until it is closed.
forward changes the position and draws; left changes only the heading.from turtle import forward, left, done
forward(100)
left(90)
forward(100)
left(90)
forward(100)
left(90)
forward(100)
left(90)
done()
When the program runs, a window opens and the turtle draws a square of side 100. In this book, the turtle drawings are printed from the turtle’s recorded path rather than as a picture of the window.
History — A turtle on the floor
The turtle comes from Logo, a programming language for children created in 1967 by a team led by Wallace Feurzeig, with Seymour Papert and Cynthia Solomon. The first turtle was a small robot on the floor, carrying a pen and drawing on large sheets of paper; it soon moved to the screen. Floor turtles were still sold to schools in the 1980s.
16.2 The for loop
Definition 16.2 (For loop and block)
A for loop repeats some lines a given number of times. for i in range(4): repeats four times the lines written under it, moved four spaces to the right. Those lines form the loop’s block: the lines that are indented the same way under a line that ends with a colon.
Definition 16.3 (Loop variable)
In for i in range(4):, i is the loop variable: a variable that the loop sets to 0 the first time, then 1, 2 and 3. It can be used inside the block.
for i in range(5):
print("i is", i)
print("done")
$ python count.py
i is 0
i is 1
i is 2
i is 3
i is 4
done
i from 0 to 4; line 3 is after the loop.range(5) counts five numbers, starting from 0: 0, 1, 2, 3, 4. The last line is not indented, so it is not part of the block: it runs once, after the loop has finished. When the block does not need the loop variable, Python programmers name it _, a name that says “not used”. The square is now four lines shorter, and a 36-sided shape would take no more lines:
from turtle import forward, left, done
for _ in range(4):
forward(100)
left(90)
done()
Indentation matters. Here the second print is not indented, so it is not in the block:
for _ in range(3):
print("Hip,")
print("hooray!")
$ python not_indented.py
Hip,
Hip,
Hip,
hooray!
16.3 Regular polygons and their angles
A regular polygon has equal sides and equal angles. To draw one, the turtle goes forward and turns by the same angle at each corner. Which angle? Walk once around any closed shape that does not cross itself and come back to the start, facing the way you started: you have turned exactly one full turn, . In a regular polygon with sides, the turns are equal, so each is degrees.
Proposition 16.4 (The turning angle of a regular polygon)
To draw a regular polygon with sides, the turtle turns by degrees at each corner: 120 for a triangle, 90 for a square, 60 for a hexagon.
Proof. A regular polygon does not cross itself, so going once around it the turtle turns one full turn, , in equal turns. Each turn is degrees. ∎
The program below writes once, at the top, so changing one number changes the polygon.
from turtle import forward, left, done
n = 6 # the number of sides: try 3, 5, 8, 36
for _ in range(n):
forward(60)
left(360 / n)
done()
A star is drawn the same way, but the turtle turns much more at each point: , five times. In all, it turns degrees, two full turns, and comes back to its start. A shape that crosses itself, like the star, can turn more than once.
from turtle import forward, right, done
for _ in range(5):
forward(150)
right(144)
done()
16.4 The loop variable and range
range can start somewhere else than 0, and can count by steps other than 1. range(a, b) counts from up to , but without ; range(a, b, s) counts from in steps of , also stopping before . A negative step counts down.
for i in range(3, 7):
print(i)
print("---")
for i in range(0, 20, 5):
print(i)
print("---")
for i in range(10, 0, -3):
print(i)
range. code/grade-6/03-for-loops-turtle/listings/ranges.py$ python ranges.py
3
4
5
6
---
0
5
10
15
---
10
7
4
1
The loop variable can also change a drawing at each round. In this spiral, the side grows with i: 0, then 5, 10, 15, and so on.
from turtle import forward, left, done
for i in range(40):
forward(5 * i) # each side is longer than the one before
left(90)
done()
16.5 A loop inside a loop
The block of a loop can hold another loop. Each time the outer loop runs once, the inner loop runs all its rounds.
Definition 16.5 (Nested loop)
A nested loop is a loop written inside the block of another loop. If the outer loop runs times and the inner loop times, the inner block runs times.
from turtle import forward, left, penup, pendown, done
for square in range(5):
size = 20 + 10 * square # 20, 30, 40, 50, 60
for _ in range(4): # one square
forward(size)
left(90)
penup()
forward(size + 15) # move to the next square
pendown()
done()
Nested loops print tables too. The multiplication table below has 5 rows, and each row has 5 numbers: the inner block runs times. Inside the curly brackets, :3 gives each number three places, so that the columns line up; end="" keeps the numbers of one row on the same line, and the print() of line 4 then ends the row.
for row in range(1, 6):
for column in range(1, 6):
print(f"{row * column:3}", end="")
print()
$ python times_table.py
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
A text can be repeated with *, as in Chapter 15: with the loop variable, this draws stairs.
for step in range(1, 6):
print("#" * step)
# signs. code/grade-6/03-for-loops-turtle/listings/stairs.py$ python stairs.py
#
##
###
####
#####
16.6 Exercises
Exercise 16.1 ★
What does for i in range(3): print(i) print?
Solution
Solution of Exercise 16.1.
Three lines: 0, 1 and 2.
Exercise 16.2 ★
Which numbers does range(2, 10, 3) give?
Solution
Solution of Exercise 16.2.
2, 5 and 8: from 2 in steps of 3, stopping before 10.
Exercise 16.3 ★
How many lines does this program print?
for a in range(3):
for b in range(4):
print(a, b)
Exercise 16.4 ★
Write a turtle program that draws an equilateral triangle of side 120.
Solution
Solution of Exercise 16.4.
Each turn is degrees.
from turtle import forward, left, done
for _ in range(3):
forward(120)
left(120)
done()
Exercise 16.5 ★★
Noor wants a regular pentagon, but her shape does not close. Find the mistake.
from turtle import forward, left, done
for _ in range(5):
forward(100)
left(60)
done()
Solution
Solution of Exercise 16.5.
A pentagon needs turns of degrees; with 60 the five turns make only 300 degrees, less than a full turn, so the turtle does not come back to its start (the drawings below). The fix is left(72).
Exercise 16.6 ★★
Tom wants to print Hip, and hooray! three times each, in turn, but Listing 16.4 prints hooray! only once. Fix it.
Exercise 16.7 ★★
Write a program that prints the 7 times table, from 7 x 1 = 7 to 7 x 10 = 70.
Solution
Solution of Exercise 16.7.
for i in range(1, 11):
print(f"7 x {i} = {7 * i}")
Exercise 16.8 ★★
Write a turtle program that draws a regular octagon of side 50.
Solution
Solution of Exercise 16.8.
Each turn is degrees.
from turtle import forward, left, done
for _ in range(8):
forward(50)
left(45)
done()
Exercise 16.9 ★★
By how many degrees must the turtle turn at each corner of a regular polygon with 10 sides? Why?
Solution
Solution of Exercise 16.9.
degrees: going once around the polygon, the turtle makes one full turn, , shared equally between the 10 corners.
Exercise 16.10 ★★★
Write a turtle program that draws a row of 5 triangles of side 50, side by side, each one starting where the last one’s base ends.
Solution
Solution of Exercise 16.10.
After each triangle, the turtle is back at the triangle’s first corner, facing right; one more forward(50) takes it to the end of the base, where the next triangle starts.
from turtle import forward, left, done
for _ in range(5): # five triangles
for _ in range(3): # the three sides of one triangle
forward(50)
left(120)
forward(50) # move along to the next one
done()
Exercise 16.11 ★★★
In Listing 16.6, the turtle turns by five times. How many full turns is that? Why does the star close?
Solution
Solution of Exercise 16.11.
: two full turns. After the five sides the turtle faces right again, as at the start. It is also back at its start: the five sides are the same length and the five turns the same, so the five points lie evenly on a circle, and the turtle jumps two points at a time until it has gone twice around the circle and reached the first point again.
Exercise 16.12 ★★★
The numbers 1, 4, 7, 10, … go up by 3 each time. Write a program that prints the first 20 of them on one line. Which is the twentieth?
Solution
Solution of Exercise 16.12.
The number of rank , counted from 0, is :
for i in range(20):
print(1 + 3 * i, end=" ")
print()
The twentieth is .
16.7 Problem: Stars of Every Size
Problem 16.1
Weekend problem — stars with points
The program below draws equal sides and turns by degrees after each one: in all, the turtle turns full turns. The two numbers and are written at the top.
from turtle import forward, left, done
n = 8 # the number of points
k = 3 # the number of full turns in all
for _ in range(n):
forward(150)
left(360 * k / n)
done()
Part I — By hand.
- For and , by how many degrees does the turtle turn each time? Which shape does it draw?
- For and , compute the angle. Which listing of this chapter draws the same shape (it turns right instead of left)?
- Draw five points on a circle, numbered 0 to 4. Join each point to the point two places further on: 0 to 2, 2 to 4, 4 to 1, and so on. Which shape do you get? Do the same jumping 3 places at a time, then compare with .
Part II — Eight points. The drawings for and from 1 to 7:
- What is the turning angle for ? Why does the turtle draw a square, and how many times does it go around it?
- What happens for ? Explain with the angle.
- Which values of draw a single line through all 8 points?
- Compare the drawings for and , then for and . What do you notice? Explain with the angles.
Part III — Counting the good stars. The drawings for :
- For , which draw all 12 points in one line? What does draw, and ?
- Run the program for , , , and and every from 1 to . Make a table: for each , how many values of give a single line through all points?
- The mathematics books prove the rule behind your table: the turtle goes through all points exactly when and have no common divisor other than 1. Check the rule on and .
- Why does a prime number of points, such as 7 or 11, give a single line for every from 1 to ?
- State the result for .
Solution
Solution of Problem 16.1.
1. degrees: a regular pentagon.
2. degrees: the five-pointed star of Listing 16.6, drawn turning left, so it is its mirror image.
3. Jumping two places gives the five-pointed star. Jumping three places gives the same star, drawn the other way round: a jump of 3 forwards is a jump of 2 backwards. In the same way, turns by to the left, which is to the right: the star again.
4. degrees: the turtle turns as for a square, but draws 8 sides, so it goes around the square twice.
5. degrees: the turtle turns right round after each side, so it walks back and forth on one segment, 4 times each way.
6. , 3, 5 and 7.
7. turns to the left, which is to the right, while turns to the left: the same star, drawn in mirror image. turns left, that is right: the octagon of , drawn the other way. In general, and give mirror drawings.
8. , 5, 7 and 11. For , the turn is : a square, gone around three times. For , it is : a triangle, gone around four times.
9. Counting the drawings:
| 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | |
|---|---|---|---|---|---|---|---|---|
| values of | 4 | 2 | 6 | 4 | 6 | 4 | 10 | 4 |
For example, for only and work (the hexagon); for , every except 3 and 6.
10. The divisors of 8 other than 1 are 2, 4 and 8: the sharing none of them are the odd ones, 1, 3, 5, 7, as in question 6. The divisors of 12 other than 1 are 2, 3, 4, 6 and 12: the from 1 to 11 that are neither even nor multiples of 3 are 1, 5, 7 and 11, as in question 8.
11. The only divisors of a prime number are 1 and itself. A number from 1 to is too small to have as a divisor, so and share only the divisor 1, and every works: 6 values for 7, 10 for 11.
12. Result. For 12 points, only , 5, 7 and 11 draw all 12 points in one line: and 11 the regular 12-sided polygon, and 7 a 12-pointed star; the other values of go several times around a smaller shape.