如果你已为这样就结束了,那么你就大错特错了,看滚动条你也知道,这篇文章没有那么简单,干货满满,让我们往下看精彩内容吧.
过圣诞节,离不开圣诞树,我们不可能自己去种一棵圣诞树,但是我们有我们吃饭的家伙,python,它可是法力无边,神通广大呢,不信吗?那么我们就来画一棵圣诞树吧!
1height = 5
2
3stars = 1
4for i in range(height):
5 print((' ' * (height - i)) + ('*' * stars))
6 stars += 2
7print((' ' * height) + '|')
效果怎么样呢?我们看一下:
确实有点过分,虽然简陋,但是仍然是一棵大树嘛,不要那么挑剔,但是重点还在后面,这样怎么能对的起我们的小伙伴呢?精彩马上回来
首先,我们看一下效果图,然后再教大家代码,代码用到了python的turtle库
1import turtle
2screen = turtle.Screen()
3screen.setup(800,600)
4circle = turtle.Turtle()
5circle.shape('circle')
6circle.color('red')
7circle.speed('fastest')
8circle.up()
9square = turtle.Turtle()
10square.shape('square')
11square.color('green')
12square.speed('fastest')
13square.up()
14circle.goto(0,280)
15circle.stamp()
16k = 0
17for i in range(1, 17):
18 y = 30*i
19 for j in range(i-k):
20 x = 30*j
21 square.goto(x,-y+280)
22 square.stamp()
23 square.goto(-x,-y+280)
24 square.stamp()
25 if i % 4 == 0:
26 x = 30*(j+1)
27 circle.color('red')
28 circle.goto(-x,-y+280)
29 circle.stamp()
30 circle.goto(x,-y+280)
31 circle.stamp()
32 k += 2
33 if i % 4 == 3:
34 x = 30*(j+1)
35 circle.color('yellow')
36 circle.goto(-x,-y+280)
37 circle.stamp()
38 circle.goto(x,-y+280)
39 circle.stamp()
40square.color('brown')
41for i in range(17,20):
42 y = 30*i
43 for j in range(3):
44 x = 30*j
45 square.goto(x,-y+280)
46 square.stamp()
47 square.goto(-x,-y+280)
48 square.stamp()
49turtle.exitonclick()
上面的是不是很棒呢?但是我们做人呢,还是要有一些追求的,我们要追求更好的效果,对不对?那么就教大家再画一棵更好的树,老规矩,直接上效果图/图片1.82M,加载可能会有些慢.此程序需要一段时间,动态图加快处理.
大家输入下面代码的时候,代码输入正确情况下,有可能pycharm是会标红线的,大家不必担心,只需要运行即可.亲测在Ubuntu下不能运行,本人运行环境在Windows10
1from turtle import *
2import random
3import time
4
5n = 80.0
6
7speed("fastest")
8screensize(bg='seashell')
9left(90)
10forward(3*n)
11color("orange", "yellow")
12begin_fill()
13left(126)
14
15for i in range(5):
16 forward(n/5)
17 right(144)
18 forward(n/5)
19 left(72)
20end_fill()
21right(126)
22
23color("dark green")
24backward(n*4.8)
25def tree(d, s):
26 if d <= 0: return
27 forward(s)
28 tree(d-1, s*.8)
29 right(120)
30 tree(d-3, s*.5)
31 right(120)
32 tree(d-3, s*.5)
33 right(120)
34 backward(s)
35tree(15, n)
36backward(n/2)
37
38for i in range(200):
39 a = 200 - 400 * random.random()
40 b = 10 - 20 * random.random()
41 up()
42 forward(b)
43 left(90)
44 forward(a)
45 down()
46 if random.randint(0, 1) == 0:
47 color('tomato')
48 else:
49 color('wheat')
50 circle(2)
51 up()
52 backward(a)
53 right(90)
54 backward(b)
55time.sleep(60)
好了,大家快去练习一下吧,最后祝大家在2018剩下的日子里每天快乐,学习再上一层楼,再见.
本文部分内容转载自程序人生的文章圣诞节!教你用python画颗圣诞树,如有侵权请告知删除.