I want to create a pentagon star with a functional function in Python, but it doesn't work...

Asked 2 years ago, Updated 2 years ago, 27 views

I am a beginner in programming.
I want to create a pentagon star with a functional function in Python, but it doesn't work...
Is there anyone who knows?
Please give me some advice.

import turtle 

star=turtle.Turtle()

def star(turtle, n = 5, d):
    angle=(180-(180*(n-2))/n))*2
    for i in range(n):
        t.forward(d)
        t.left(angle)
    return angle

US>turtle.done()

python

2022-09-30 21:34

2 Answers

There are some problems with the code.

  • Duplicate variable name, module name, and function name.For example, モジュールmodule turtle and argument name turtle. /
  • t is undefined.The first statement should be import Turtle as and it will work.
  • angle is a pentagonal star, so it's better to fix it 144 degrees x 5 times
  • The argument "turtle" or "n" for the function star is not required.
  • The Turtle code works without defining it
  • The defined function is not working.Write a code to move it

The finished form is below.
import turtle as t

def star(length):
    t.pd()
    for i in range (5):
        t.fd(length)
        t.lt(144)
    t.pu()

if__name__=="__main__":
    star (150)


2022-09-30 21:34

First, try writing the turtle graphic in a way similar to the original logo language.If you're new to programming, you might want to write this way and get used to it.

from Turtle import*

def star(d):
    n = 5
    angle=(180-(180*(n-2))/n))*2
    for i in range(n):
        forward(d)
        left(angle)

star(100)
done()

The code in the question is object-oriented writing.In this case, create a turtleneck with turtle.Turtle() and name it by substituting the variable.Therefore, it is not recommended to name a variable with the same name as the function, star.If there are people with the same name, it will be complicated, so let's give them a name that can be distinguished from others.For more information, see the class page in the official tutorial.

import turtle 
tom=turtle.Turtle()

If you create a named turtleneck, you need to pass the variable to the function star before you know it, so you need the corresponding provisional argument.In addition, the temporary argument n=5 is optional when calling because it specifies the default value.So, you have to put it after the normal provisional argument.For more information, see the official tutorial defining the function.

def star(t,d,n=5): 

Based on the above information, the question is to create Python pentagon stars with functional functions, so if you write the code, it will look like the following:

import turtle

def star(t,d,n=5):
    angle=(180-(180*(n-2))/n))*2
    for i in range(n):
        t.forward(d)
        t.left(angle)

tom=turtle.Turtle()
star(tom,100)
US>turtle.done()   


2022-09-30 21:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.