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)

结果

相关推荐
snow@li3 分钟前
服务器:配置中心 Nacos / Apollo 详解
运维·服务器
Odoo老杨7 分钟前
如何直接在线定制修改 Odoo UI界面?
css·python·crm·odoo·erp·中小企业数字化
SEO_juper10 分钟前
不同国家服务器、域名选择,提升本地谷歌抓取优先级
运维·服务器·seo·外贸·geo·独立站·跨境电商独立站
DeboPXK13 分钟前
NSK VH25EM 高防尘法兰型导轨技术手册
服务器·网络·数据库·经验分享·规格说明书
派大鑫wink31 分钟前
Java 高级编程技巧(生产级实用,覆盖性能、并发、设计、JVM、语法、避坑)
开发语言·python
超级赛博搬砖工32 分钟前
SEO代理解析:成功搜索引擎抓取你需要了解的事项
大数据·运维·服务器·网络
换个昵称都难35 分钟前
webrtc peerconnection_server 模块介绍
运维·服务器·webrtc
子嘉11336 分钟前
【无标题】
python
冷小鱼37 分钟前
TensorFlow 2.21 进阶实战:从训练优化到生产部署的完整指南
人工智能·pytorch·python·tensorflow