python 打印圣诞树

1. 打印一棵简单的圣诞树

python 复制代码
def print_christmas_tree(height):
    for i in range(height):
        # 打印每一层的空格
        print(" " * (height - i - 1), end="")
        # 打印每一层的星号
        print("*" * (2 * i + 1))
    # 打印树干
    for _ in range(2):
        print(" " * (height - 1) + "|")

# 调用函数打印圣诞树
tree_height = 8  # 你可以修改树的高度
print_christmas_tree(tree_height)

结果

2. 更炫酷的圣诞树代码

python 复制代码
import random

def print_cool_christmas_tree(height):
    decorations = ['*', 'o', 'x', '+']  # 树的装饰品
    for i in range(height):
        # 打印每一层的空格
        print(" " * (height - i - 1), end="")
        # 打印每一层的装饰品或星号
        for j in range(2 * i + 1):
            if random.random() > 0.8:  # 随机决定是否放装饰品
                print(random.choice(decorations), end="")
            else:
                print("*", end="")
        print()  # 换行

    # 打印树干
    for _ in range(3):
        print(" " * (height - 2) + "|||")

# 调用函数打印圣诞树
tree_height = 10  # 可以修改树的高度
print_cool_christmas_tree(tree_height)

结果

3. 带颜色的圣诞树

python 复制代码
from colorama import Fore, Style, init
import random
import time

# 初始化 colorama
init(autoreset=True)

def print_colored_christmas_tree(height):
    decorations = [Fore.RED + '*', Fore.GREEN + 'o', Fore.YELLOW + 'x', Fore.CYAN + '+']
    for i in range(height):
        # 打印空格
        print(" " * (height - i - 1), end="")
        # 打印随机装饰品
        for j in range(2 * i + 1):
            if random.random() > 0.8:  # 控制装饰品概率
                print(random.choice(decorations), end="")
            else:
                print(Fore.GREEN + "*", end="")
        print()  # 换行

    # 打印彩色树干
    for _ in range(3):
        print(" " * (height - 2) + Fore.MAGENTA + "|||")

# 动态打印圣诞树
def dynamic_christmas_tree(height):
    for _ in range(5):  # 打印5次变化的树
        print("\033c", end="")  # 清屏
        print_colored_christmas_tree(height)
        time.sleep(0.5)  # 暂停0.5秒

# 调用函数
dynamic_christmas_tree(10)

结果

相关推荐
瓦学妹10 分钟前
什么是网络索引?它是如何工作的?
大数据·网络·python·网络爬虫
天天爱吃肉821830 分钟前
商用车多体动力学实战笔记|第6篇:动力传动系统(发动机、变速箱、分动器、TCS、LSD限滑差速)
大数据·人工智能·笔记·python·嵌入式硬件·汽车
海盗12341 小时前
微软技术周报 ——2026-08-03
后端·python·microsoft·c#·.netcore
大数据魔法师1 小时前
【最全详解】DuckDB Python 全套 API 语法、参数与实战用法(零基础全覆盖)
python·数据分析
清水迎朝阳2 小时前
客户端软件 — 用户统计方案
服务器·c++·客户端·用户统计
MC皮蛋侠客2 小时前
SQLAlchemy 系列(七):高级建模与高效写入——批量 DML、方言与扩展
数据库·python
会编程的土豆2 小时前
Go 模板初识
linux·运维·服务器
腾讯蓝鲸智云2 小时前
标杆客户实践提炼:CFlow 版本价值流模板实战指南
运维·服务器·自动化·云计算·devops
Zane19943 小时前
@property 到底是怎么把方法伪装成属性的?一文吃透 property、staticmethod、classmethod
后端·python
阿标的博客3 小时前
Active Directory 组织单位和用户
服务器