Regular Polygons
At the moment, the
while statement is more convenient for us because it takes
a
logical condition for executing the subordinate instructions, and we can play with it graphically.
EXAMPLE
I aim to create a program that reads from the keyboard the
number of sides of a
regular polygon
to be drawn. For space considerations, I have chosen a side length of
50 pixels, a value I will not read
from the keyboard, although... it is easy to modify the program later.
Definition. A
regular polygon is a simple polygon that has
all sides and angles equal.
Examples: an
equilateral triangle, a
square, a
pentagon, a
hexagon, etc.:
We can also try a
heptagon,
octagon,
decagon, or...
dodecagon.
When mathematics meets computer science, cool things happen! Execute the code bellow:
HOW DID WE THINK ABOUT IT?
Well... first, I read the number of sides from the keyboard and stored it in the integer variable
n.
Then, for a regular polygon with
n sides, we have
n angles, so the variable
u holds this value,
which is
3600 divided by
n to ensure
fine precision.
The
while loop must repeat exactly
n times, so I use a
control variable,
the variable
sides, which initially holds
1. At each step, it is
incremented (
increased)
by one (see line of code 12). When it reaches the value
n+1, the
while
loop stops executing, so it’s perfect.
HOW DO WE READ THIS?
As long as the value of sides is less than or equal to the given value, draw the side,
rotate by u degrees, and then increment the counter, sides! When the number of
sides is exceeded, I stop!
Note. If
n=1, the polygon is called a
monogon, and if
n=2, a
digon.
Rectangle - while and if
For a rectangle, it’s similar, but I need
a decision. When do I advance the number of pixels
corresponding to the
long or short side?!?
First, I advance for the first side, so an
odd number. Then, the second side, an
even
number... analyze and run the program below:
import turtle
t = turtle.Turtle()
n = int(input("n="))
m = int(input("m="))
sides = 1
while sides <= 4:
if sides % 2 == 1: # odd number?
t.fd(n)
else:
t.fd(m)
t.left(90)
sides = sides + 1
Interesting, right?
All instructions are useful at some point.
Proceed to the next page.