# Python 送你一棵圣诞树

Crossin先生

1、极简版

``````

height = 11
for i in range(height):
print((' ' * (height - i)) + ('*' * ((2 * i) + 1)))
print((' ' * height) + '|')

``````

2、彩色版

``````

import random
height = 11
for i in range(height):
print(' ' * (height - i), end='')
for j in range((2 * i) + 1):
if random.random() < 0.1:
color = random.choice(['\033[1;31m', '\033[33m', '\033[1;34m'])
print(color, end='')  # 彩灯
else:
print('\033[32m', end='')  # 绿色
print('*', end='')
print()
print((' ' * height) + '|')

``````

3、海龟版

Python 里有个自带的绘图工具叫 `turtle`，编程教室之前介绍过《【编程课堂】海龟作图》，用它也能画圣诞树。完整代码见文末地址，核心绘制代码：

``````

# 创建画板
import turtle
screen = turtle.Screen()
screen.setup(800,600)
# 画红色圆
circle = turtle.Turtle()
circle.shape('circle')
circle.color('red')
circle.up()
circle.goto(0,100)
circle.stamp()
# 画绿色方块
square = turtle.Turtle()
square.shape('square')
square.color('green')
square.up()
square.goto(0,200)
square.stamp()
# 暂停，点击后退出
turtle.exitonclick()

``````

4、海龟分形版

``````

n = 50
from turtle import *
speed("fastest")
left(90)
forward(3*n)
# 顶部五角星略过
color("dark green")
backward(n*4.8)
def tree(d, s):
if d <= 0:
return
forward(s)
tree(d-1, s*.8)
right(120)
tree(d-3, s*.5)
right(120)
tree(d-3, s*.5)
right(120)
backward(s)
tree(15, n)
backward(n/2)
exitonclick()

``````

5、炫彩版

``````

import platform
import os
os_name = platform.uname()[0]
IS_WIN = os_name == 'Windows'
os.system('cls' if IS_WIN else 'clear')

``````

【注】

R&Python绘制圣诞树-EasyCharts

(圣诞礼物)在终端下画个圣诞树陪你过节-Medici.Yan
http://blog.evalbug.com/2015/12/25/py_fun_0/

════

936 声望
192 粉丝
0 条评论