My professor has asked our class to write a Python function that does as following:
Draw a regular n-pointed star with side d - in a function named star(turtle, n, d)
Here's the code that I have so far:
def star(turtle, n, d):
angle = (180-((180*(n-2))/n))*2
for i in range(n):
t.forward(d)
t.left(angle)
return angle
The problem that I am experiencing is that my function is only able to draw stars with odd numbers of corners (5, 7, 9-sided stars). When I ask it to draw a star with an even number of sides, it outputs polygon with sides n/2. So asking to draw an 8-sided star outputs a square, 6-sided gives a triangle, and so forth.
I've tried altering the angle formula many times, but it never works with any given n.
Thanks for helping!
You can draw most of the odd and even pointed stars with the same code by using a GCD routine to look for coprimes and treating failures as exceptions:
import sys
import turtle
from time import sleep
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def normal_star(size, color, points):
if points <= 4:
raise ValueError('Not enough points')
turtle.color(color)
for coprime in range(points // 2, 1, -1):
if gcd(points, coprime) == 1:
print("({},{})".format(points, coprime), file=sys.stderr)
start = turtle.position()
for _ in range(points):
turtle.forward(size)
turtle.left(360.0 / points * coprime)
turtle.setposition(start)
return
abnormal_star(size, color, points)
def abnormal_star(size, color, points):
# deal with special cases here
print("Exception:", points, file=sys.stderr)
for points in range(5, 20):
turtle.reset()
normal_star(200, 'red', points)
sleep(5)
turtle.exitonclick()
For points from 5 to 20, this only fails to find a solution for 6 which you'll need to treat as an exception, i.e. specialized code or just letting the user know it's an exception you can't handle:
> python3 test.py
(5,2)
Exception: 6
(7,3)
(8,3)
(9,4)
(10,3)
(11,5)
(12,5)
(13,6)
(14,5)
(15,7)
(16,7)
(17,8)
(18,7)
(19,9)
(20,9)
>
Output example for arguments 200,'red',10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With