教你用Python画了一棵圣诞树!圣诞节给女朋友制作个小惊喜

如何用Python画一个圣诞树呢?

最简单:

 
  1. height = 5

  2. stars = 1

  3. for i in range(height):

  4. print((' ' * (height - i)) + ('*' * stars))

  5. stars += 2

  6. print((' ' * height) + '|')

效果:

 

 

哈哈哈哈,总有一种骗了大家的感觉。

其实本文是想介绍Turtle库来画圣诞树。

 
  1. import turtle

  2. screen = turtle.Screen()

  3. screen.setup(375, 700)

  4.  
  5. circle = turtle.Turtle()

  6. circle.shape('circle')

  7. circle.color('red')

  8. circle.speed('fastest')

  9. circle.up()

  10. square = turtle.Turtle()

  11. square.shape('square')

  12. square.color('green')

  13. square.speed('fastest')

  14. square.up()

  15. circle.goto(0, 280)

  16. circle.stamp()

  17. k = 0

  18. for i in range(1, 13):

  19. y = 30 * i

  20. for j in range(i - k):

  21. x = 30 * j

  22. square.goto(x, -y + 280)

  23. square.stamp()

  24. square.goto(-x, -y + 280)

  25. square.stamp()

  26. if i % 4 == 0:

  27. x = 30 * (j + 1)

  28. circle.color('red')

  29. circle.goto(-x, -y + 280)

  30. circle.stamp()

  31. circle.goto(x, -y + 280)

  32. circle.stamp()

  33. k += 3

  34. if i % 4 == 3:

  35. x = 30 * (j + 1)

  36. circle.color('yellow')

  37. circle.goto(-x, -y + 280)

  38. circle.stamp()

  39. circle.goto(x, -y + 280)

  40. circle.stamp()

  41. square.color('brown')

  42. for i in range(13, 17):

  43. y = 30 * i

  44. for j in range(2):

  45. x = 30 * j

  46. square.goto(x, -y + 280)

  47. square.stamp()

  48. square.goto(-x, -y + 280)

  49. square.stamp()

效果:

 

 

方法二:

 
  1. import turtle

  2. # 定义圣诞树的绿叶函数

  3. def tree(d, s):

  4. if d <= 0:

  5. return

  6. turtle.forward(s)

  7. tree(d - 1, s * .8)

  8. turtle.right(120)

  9. tree(d - 3, s * .5)

  10. turtle.right(120)

  11. tree(d - 3, s * .5)

  12. turtle.right(120)

  13. turtle.backward(s)

  14. n = 100

  15. """ 设置绘图速度

  16. 'fastest' : 0

  17. 'fast' : 10

  18. 'normal' : 6

  19. 'slow' : 3

  20. 'slowest' : 1

  21. """

  22. turtle.speed('fastest') # 设置速度

  23. turtle.left(90)

  24. turtle.forward(3 * n)

  25. turtle.color("orange", "yellow")

  26. turtle.left(126)

  27. # turtle.begin_fill()

  28. for i in range(5):

  29. turtle.forward(n / 5)

  30. turtle.right(144)

  31. turtle.forward(n / 5)

  32. turtle.left(72)

  33. turtle.end_fill()

  34. turtle.right(126)

  35. turtle.color("dark green")

  36. turtle.backward(n * 4.8)

  37. # 执行函数

  38. tree(15, n)

  39. turtle.backward(n / 5)

效果:

 

后记

近期有很多朋友通过私信咨询有关Python学习问题。为便于交流,点击蓝色自己加入讨论解答资源基地

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值