কম্পিউটার বিজ্ঞান · বই 1 · শ্রেণি 1–9

Primary & Middle School Computer Science

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: 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 dd steps straight ahead), left(a) and right(a) (turn on the spot by aa 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.

The turtle’s state is its position and its heading (the red arrow). forward changes the position and draws; left changes only the heading.
The turtle’s state is its position and its heading (the red arrow). 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()
Listing 16.1. A square, the long way. code/grade-6/03-for-loops-turtle/listings/square_long.py

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.

A floor turtle robot of the 1980s, with a drawing it made.
A floor turtle robot of the 1980s, with a drawing it made.

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")
Listing 16.2. A loop that shows its loop variable. code/grade-6/03-for-loops-turtle/listings/count.py
$ python count.py
i is 0
i is 1
i is 2
i is 3
i is 4
done
Output 16.1. Five rounds, with 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()
Listing 16.3. The same square, with a loop. code/grade-6/03-for-loops-turtle/listings/square.py

Indentation matters. Here the second print is not indented, so it is not in the block:

for _ in range(3):
    print("Hip,")
print("hooray!")
Listing 16.4. Which lines repeat? code/grade-6/03-for-loops-turtle/listings/not_indented.py
$ python not_indented.py
Hip,
Hip,
Hip,
hooray!
Output 16.2. Only the indented line repeats.

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, 360∘360^\circ. In a regular polygon with nn sides, the nn turns are equal, so each is 360÷n360 \div n degrees.

A regular hexagon. At each corner the turtle turns by 60 (red), from the dashed line it was following to the next side. The six turns put end to end make one full turn: 6 × 60 = 360.
A regular hexagon. At each corner the turtle turns by 60∘60^\circ (red), from the dashed line it was following to the next side. The six turns put end to end make one full turn: 6×60=3606 \times 60 = 360.

Proposition 16.4 (The turning angle of a regular polygon)

To draw a regular polygon with nn sides, the turtle turns by 360÷n360 \div n 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, 360∘360^\circ, in nn equal turns. Each turn is 360÷n360 \div n degrees. ∎

The program below writes nn 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()
Listing 16.5. Any regular polygon. code/grade-6/03-for-loops-turtle/listings/polygon.py

A star is drawn the same way, but the turtle turns much more at each point: 144∘144^\circ, five times. In all, it turns 5×144=7205 \times 144 = 720 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()
Listing 16.6. A five-pointed star. code/grade-6/03-for-loops-turtle/listings/star.py

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 aa up to bb, but without bb; range(a, b, s) counts from aa in steps of ss, also stopping before bb. 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)
Listing 16.7. Three ways to use 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
Output 16.3. The last number is never reached: 7, 20 and 0 are not printed.

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()
Listing 16.8. A square spiral. code/grade-6/03-for-loops-turtle/listings/spiral.py
Four drawings, from the turtle’s recorded path. The red dot is the start. The star’s five turns of 144 make two full turns; the spiral’s sides grow by 5 at each turn.
Four drawings, from the turtle’s recorded path. The red dot is the start. The star’s five turns of 144∘144^\circ make two full turns; the spiral’s sides grow by 5 at each turn.

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 aa times and the inner loop bb times, the inner block runs a×ba \times b 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()
Listing 16.9. A row of five growing squares. code/grade-6/03-for-loops-turtle/listings/row_of_squares.py
The outer loop runs 5 times; each time, the inner loop draws the 4 sides of one square, then the turtle moves on with its pen up.
The outer loop runs 5 times; each time, the inner loop draws the 4 sides of one square, then the turtle moves on with its pen up.

Nested loops print tables too. The multiplication table below has 5 rows, and each row has 5 numbers: the inner block runs 5×5=255 \times 5 = 25 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()
Listing 16.10. A multiplication table. code/grade-6/03-for-loops-turtle/listings/times_table.py
$ 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
Output 16.4. Row rr, column cc holds r×cr \times c.

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)
Listing 16.11. Stairs of # signs. code/grade-6/03-for-loops-turtle/listings/stairs.py
$ python stairs.py
#
##
###
####
#####
Output 16.5. Row nn has nn signs.

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)
Listing 16.12. Count before running. code/grade-6/03-for-loops-turtle/exercises/nested_count.py
Solution

Solution of Exercise 16.3.

12 lines: the outer loop runs 3 times, and each time the inner loop prints 4 lines, from 0 0 to 2 3.

Exercise 16.4 ★

Write a turtle program that draws an equilateral triangle of side 120.

Solution

Solution of Exercise 16.4.

Each turn is 360÷3=120360 \div 3 = 120 degrees.

from turtle import forward, left, done

for _ in range(3):
    forward(120)
    left(120)
done()
An equilateral triangle. code/grade-6/03-for-loops-turtle/exercises/triangle.py

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()
Listing 16.13. A pentagon that does not close. code/grade-6/03-for-loops-turtle/exercises/open_polygon.py
Solution

Solution of Exercise 16.5.

A pentagon needs turns of 360÷5=72360 \div 5 = 72 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.

Solution

Solution of Exercise 16.6.

Indent the second print, so that it is in the block:

for _ in range(3):
    print("Hip,")
    print("hooray!")
Both lines in the block. code/grade-6/03-for-loops-turtle/exercises/hip.py

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}")
The 7 times table. code/grade-6/03-for-loops-turtle/exercises/seven.py

Exercise 16.8 ★★

Write a turtle program that draws a regular octagon of side 50.

Solution

Solution of Exercise 16.8.

Each turn is 360÷8=45360 \div 8 = 45 degrees.

from turtle import forward, left, done

for _ in range(8):
    forward(50)
    left(45)
done()
A regular octagon. code/grade-6/03-for-loops-turtle/exercises/octagon.py

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.

360÷10=36360 \div 10 = 36 degrees: going once around the polygon, the turtle makes one full turn, 360∘360^\circ, 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()
A row of triangles. code/grade-6/03-for-loops-turtle/exercises/row_of_triangles.py
The drawings of exercises 4, 5, 8 and 10. With turns of 60 degrees, the “pentagon” stops short of its start.
The drawings of exercises 4, 5, 8 and 10. With turns of 60 degrees, the “pentagon” stops short of its start.

Exercise 16.11 ★★★

In Listing 16.6, the turtle turns by 144∘144^\circ five times. How many full turns is that? Why does the star close?

Solution

Solution of Exercise 16.11.

5×144=720=2×3605 \times 144 = 720 = 2 \times 360: 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 ii, counted from 0, is 1+3×i1 + 3 \times i:

for i in range(20):
    print(1 + 3 * i, end=" ")
print()
The first 20 numbers. code/grade-6/03-for-loops-turtle/exercises/sequence.py

The twentieth is 1+3×19=581 + 3 \times 19 = 58.

16.7 Problem: Stars of Every Size

Problem 16.1

Weekend problem — stars with nn points

The program below draws nn equal sides and turns by 360×k÷n360 \times k \div n degrees after each one: in all, the turtle turns kk full turns. The two numbers nn and kk 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()
Listing 16.14. A star with nn points and kk full turns. code/grade-6/03-for-loops-turtle/listings/stars.py

Part I — By hand.

  1. For n=5n = 5 and k=1k = 1, by how many degrees does the turtle turn each time? Which shape does it draw?
  2. For n=5n = 5 and k=2k = 2, compute the angle. Which listing of this chapter draws the same shape (it turns right instead of left)?
  3. 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 k=3k = 3.

Part II — Eight points. The drawings for n=8n = 8 and kk from 1 to 7:

Eight sides of length 150, turning 360 × k 8 degrees each time. The red dot is the start.
Eight sides of length 150, turning 360×k÷8360 \times k \div 8 degrees each time. The red dot is the start.
  1. What is the turning angle for k=2k = 2? Why does the turtle draw a square, and how many times does it go around it?
  2. What happens for k=4k = 4? Explain with the angle.
  3. Which values of kk draw a single line through all 8 points?
  4. Compare the drawings for k=3k = 3 and k=5k = 5, then for k=1k = 1 and k=7k = 7. What do you notice? Explain with the angles.

Part III — Counting the good stars. The drawings for n=12n = 12:

Twelve sides, turning 360 × k 12 = 30 × k degrees.
Twelve sides, turning 360×k÷12=30×k360 \times k \div 12 = 30 \times k degrees.
  1. For n=12n = 12, which kk draw all 12 points in one line? What does k=3k = 3 draw, and k=4k = 4?
  2. Run the program for n=6n = 6, 77, 99, 1010 and 1111 and every kk from 1 to n−1n - 1. Make a table: for each nn, how many values of kk give a single line through all nn points?
  3. The mathematics books prove the rule behind your table: the turtle goes through all nn points exactly when nn and kk have no common divisor other than 1. Check the rule on n=8n = 8 and n=12n = 12.
  4. Why does a prime number of points, such as 7 or 11, give a single line for every kk from 1 to n−1n - 1?
  5. State the result for n=12n = 12.
Solution

Solution of Problem 16.1.

1. 360×1÷5=72360 \times 1 \div 5 = 72 degrees: a regular pentagon.

2. 360×2÷5=144360 \times 2 \div 5 = 144 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, k=3k = 3 turns by 216∘216^\circ to the left, which is 360−216=144∘360 - 216 = 144^\circ to the right: the star again.

Five points: the pentagon, and the star drawn in both directions.
Five points: the pentagon, and the star drawn in both directions.

4. 360×2÷8=90360 \times 2 \div 8 = 90 degrees: the turtle turns as for a square, but draws 8 sides, so it goes around the square twice.

5. 360×4÷8=180360 \times 4 \div 8 = 180 degrees: the turtle turns right round after each side, so it walks back and forth on one segment, 4 times each way.

6. k=1k = 1, 3, 5 and 7.

7. k=5k = 5 turns 225∘225^\circ to the left, which is 135∘135^\circ to the right, while k=3k = 3 turns 135∘135^\circ to the left: the same star, drawn in mirror image. k=7k = 7 turns 315∘315^\circ left, that is 45∘45^\circ right: the octagon of k=1k = 1, drawn the other way. In general, kk and n−kn - k give mirror drawings.

8. k=1k = 1, 5, 7 and 11. For k=3k = 3, the turn is 90∘90^\circ: a square, gone around three times. For k=4k = 4, it is 120∘120^\circ: a triangle, gone around four times.

9. Counting the drawings:

nn56789101112
values of kk426464104

For example, for n=6n = 6 only k=1k = 1 and k=5k = 5 work (the hexagon); for n=9n = 9, every kk except 3 and 6.

10. The divisors of 8 other than 1 are 2, 4 and 8: the kk 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 kk 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 nn are 1 and nn itself. A number kk from 1 to n−1n - 1 is too small to have nn as a divisor, so kk and nn share only the divisor 1, and every kk works: 6 values for 7, 10 for 11.

12. Result. For 12 points, only k=1k = 1, 5, 7 and 11 draw all 12 points in one line: k=1k = 1 and 11 the regular 12-sided polygon, k=5k = 5 and 7 a 12-pointed star; the other values of kk go several times around a smaller shape.

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো