下面的Python代码什么都不做,我想知道为什么

2024-09-28 22:32:11 发布

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

我试过一本书中的Python代码,但它不起作用。我还复制粘贴了它,以确保它不是我的错,仍然无法工作。其他使用turtle的类似示例工作得很好,但这一个无法运行。没有错误,没有警告,它什么也不做

怎么了?我是Python方面的新手

import turtle


def draw_triangle(points, color, my_turtle):
    my_turtle.fillcolor(color)
    my_turtle.up()
    my_turtle.goto(points[0][0], points[0][1])
    my_turtle.down()
    my_turtle.begin_fill()
    my_turtle.goto(points[1][0], points[1][1])
    my_turtle.goto(points[2][0], points[2][1])
    my_turtle.goto(points[0][0], points[0][1])
    my_turtle.end_fill()


def get_mid(p1, p2):
    return ((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2)


def sierpinski(points, degree, my_turtle):
    color_map = ['blue', 'red', 'green', 'white', 'yellow',
    'violet', 'orange']
    draw_triangle(points, color_map[degree], my_turtle)
    if degree > 0:
        sierpinski([points[0],
            get_mid(points[0], points[1]),
            get_mid(points[0], points[2])],
            degree - 1, my_turtle)
        sierpinski([points[1],
            get_mid(points[0], points[1]),
            get_mid(points[1], points[2])],
            degree - 1, my_turtle)
        sierpinski([points[2],
            get_mid(points[2], points[1]),
            get_mid(points[0], points[2])],
            degree - 1, my_turtle)


def main():
    my_turtle = turtle.Turtle()
    my_win = turtle.Screen()
    my_points = [[-100, -50], [0, 100], [100, -50]]
    sierpinski(my_points, 3, my_turtle)
    my_win.exitonclick()

Tags: getmydeffillpointscolortrianglep2
3条回答

在脚本末尾添加以下代码段,这是编码约定

if __name__ == '__main__':
    main()

如果您喜欢函数式编码样式,实际上可以在现有代码的末尾添加main()

好的,在python中定义一个函数后,必须调用它。尝试在代码中的某个位置调用它,因为Python解释器逐行垂直运行代码。无论何时何地运行该程序,都可以通过尝试-function()-来调用该函数

您已经定义了函数,但从未调用过它们。如果你加一个

main()  # note that there is no indentation here

到文件的最后,您将实际运行main函数并开始执行

相关问题 更多 >