Hello, I’m Yue Chuang.
In the last article, I showed you how to draw kites in Turtle, but the code is not beautiful enough. This article will show you how to optimize it.
The first is to draw a kite code optimization, the original code to see a piece. Optimized code:
import turtle
def kite(speed=1, position_x=0, position_y=0) :
""" "Speed: brush speed position_x: x coordinate position_Y: y coordinate default: the initial value of the coordinate is 0 """ "
turtle.speed(speed)
turtle.goto(position_x, position_y)
for i in range(30):
turtle.forward(i)
turtle.left(90)
turtle.exitonclick() # Prevent the window from disappearing after running
if __name__ == '__main__':
kite(speed=2, position_x=-200, position_y=200)
Copy the code
The running results are as follows:
Next, let’s optimize to draw the four corners of the kite, but do not need the kite string.
import turtle
def kite(speed=1, position_x=0, position_y=0, exit_click=False) :
""" "Speed: paint speed position_x: x coordinate position_y: y coordinate exit_click: whether to leave the window after drawing default: the initial value of the coordinate is 0 """
turtle.speed(speed)
turtle.pen(pendown=False)
turtle.goto(position_x, position_y)
turtle.pen(pendown=True)
# turtle.pendown()
for i in range(160):
turtle.forward(i)
turtle.left(90)
if exit_click:
# Prevent the window from disappearing after running
turtle.exitonclick()
if __name__ == '__main__':
kite(speed=120, position_x=-200, position_y=200)
kite(speed=120, position_x=-200, position_y=-200)
kite(speed=120, position_x=0, position_y=0)
kite(speed=120, position_x=200, position_y=200)
kite(speed=120, position_x=200, position_y=-200, exit_click=True)
Copy the code
AI yue chuang · launched tutorials, including “Python language tutorials, C++ tutorials, algorithm/data structure tutorials”, all one-to-one teaching: one-to-one tutoring + one-to-one q&a + assignment + project practice, etc. QQ, wechat online, at any time to respond! V: Jiabcdefh