Python case 2 - turtle library to draw pentagram V_6.0

Hello everyone, I'm cabbage carrot balls

Life is too short, Python is a song

insert image description here
Drawing Pentagram V_6.0


project import

Version 6.0: Use recursive function to achieve the drawing of repeating pentagrams

Project analysis - clarifying ideas

  1. Analyze the problem: The computational part of the analysis problem
  2. Defining the problem: dividing the input, processing, and output parts of the problem (IPO)
  3. Designing Algorithms: The Heart of the Computational Section

Drawing Pentagram V_6.0

Knowledge point learning – from the ground up


recursive function

  • The way in which a function definition calls a function itself is called recursion

  • Ability to solve important problems very succinctly

  • Each time the function is called, the function parameters will be temporarily stored, and there is no mutual influence. When the termination condition is reached, each function ends the operation layer by layer. When returning the calculation result, pay attention to the construction of the termination condition, otherwise the recursion cannot return the result normally.

def digui (num)				#定义递归函数
	print(num)				#输出当前教字
	if num>0:				#判断当前数字是否>0
		digui(nun-1)		#调用函数本身
	else:
		print('----')
	print (num)				#再次输出当前数字
digui(3)
#运行过程
digui (3)
	print (3)
	if 3>0:
 		digui (2):		#调用函数本身
 		print(2)
		if 2>0
			digui(1) 	#调用函数木身
 			print (1if 1>0
 				digui (0):	#调用函数本身
 				print (0)
				if 0>0:
 				digui(num-1)	#调用函数本身
 				else :
 					print ('---')
 				print (0)
			print(1) 
 	print (2)
 print (3)

recursion pros and cons

advantage:

Recursion makes code look cleaner and more elegant

Complex tasks can be broken down into simpler subproblems with recursion It is easier to use recursion than to use some nested iterations

shortcoming:

Recursive logic is hard to debug and follow

Recursive algorithms are less efficient to solve problems. In the process of recursive call, the system opens up a stack to store the return point, local quantity, etc. of each layer. Excessive recursion can easily lead to stack overflow and so on.

Hands-on programming – hands-on, let the program run

reference code


"""
作者:白菜胡萝丸子
版本6.0:使用递归函数实现重复五角星的绘制
"""

import turtle


def pentagram(side_length):
    i = 0
    while i < 5:
        turtle.forward(side_length)
        turtle.right(144)
        i = i + 1
    side_length = side_length + 100
    if side_length <= 500:
        pentagram(side_length)


def main():
    turtle.speed(10)
    side = 100
    pentagram(side)

    turtle.exitonclick()


if __name__ == "__main__":
    main()

Results of the


Draw a five-pointed star


Take it to the next level - let the program evolve a little bit

In addition to the turtles for drawing graphics, is there any other method or library for drawing graphics in Python? Canvas control

Guess you like

Origin blog.csdn.net/coco264/article/details/123577060