使函数递归

2024-04-26 21:51:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将下面的函数转换为递归函数,但尝试时不断出现错误。你知道吗

TypeError: unsupported operand type(s) for *: 'float' and 'NoneType'

def turtle_spiral(forward):

    minus = 8

    t = turtle.Turtle()

    t.pendown()

    t.shape("turtle")
    #while forward > 10:

    randm = random.randrange(5)
    colours = ["blue", "orange", "yellow", "green",   "purple","black","red","pink"]

    t.goto(-100,0)

    if forward <= 10:
        return False

    else:
        t.color(colours[randm])
        #t.speed(10)
        t.fd(turtle_spiral(forward*minus))
        #t.circle(forward, 360)
        t.right(90)
        #forward -= minus


turtle_spiral(100)

wd.mainloop()

Tags: and函数fortype错误floatforwardturtle
2条回答

我已经尝试过修改你的代码来做我认为你想做的事情:

import turtle
import random

def turtle_spiral(forward):

    minus = 8
    randm = random.randrange(5)
    colours = ["blue", "orange", "yellow", "green",   "purple","black","red","pink"]

    if forward <= 10:
        return 0
    else:
        t.color(colours[randm])
        t.right(90)
        t.fd(forward)
        return turtle_spiral(forward-minus)

t = turtle.Turtle()

t.pendown()

t.shape("turtle")
turtle_spiral(100)

递归的关键是定义递归的端点。在你的例子中,是当海龟被要求前进不到10英里的时候。在结束点,递归函数不应该调用自身,而应该返回。你知道吗

在其他情况下,我们希望函数在某个点上使用一个参数来调用自己,使它更接近端点。在您的例子中,这个参数是forward-minus,并且随着turtle_spiral递归调用它自己,这个值将越来越接近结束条件。你知道吗

尽管John Sharp很好地分析了你的代码,得出了你想要海龟做的事情,但我阅读了字里行间的代码,也就是你注释掉的代码,得出了你真正希望海龟能做的事情:

from turtle import Turtle, Screen
from random import choice, randrange

LENGTH = 200
LIMIT = 10
DELTA = 16

colors = ["blue", "orange", "cyan", "green", "purple", "black", "red", "magenta"]

def turtle_spiral(turtle, length, delta, limit):

    if length < limit:
        return

    extent = 360 / delta

    for radius in range(delta):
        turtle.circle(length - radius, extent=extent)
        if randrange(delta) == 0:
            turtle.color(choice(colors))

    turtle_spiral(turtle, length - delta, delta, limit)

yertle = Turtle(shape="turtle", visible=False)

yertle.speed("fastest")

yertle.penup()
yertle.sety(-LENGTH)
yertle.pendown()

yertle.showturtle()

turtle_spiral(yertle, LENGTH, DELTA, LIMIT)

screen = Screen()
screen.exitonclick()

我还加入了一些风格的变化,看看它们是否对你有意义。例如:turtle_spiral()不需要返回值,任何东西都不会查看结果;从运行的代码中获取全局定义,如colors数组;将海龟和其他信息作为带有事件计时器的参数传递到turtle_spiral(),然后一次可以运行多个;让你的乌龟隐形,直到你得到它的起点,然后揭示它。你知道吗

enter image description here

相关问题 更多 >