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)

结果

相关推荐
筏.k3 分钟前
grep、wc 与管道符快速上手指南
linux
狐凄6 分钟前
Python实例题:Python计算线性代数
开发语言·python·线性代数
西猫雷婶7 分钟前
pytorch基本运算-导数和f-string
人工智能·pytorch·python
Johny_Zhao8 分钟前
华为MAAS、阿里云PAI、亚马逊AWS SageMaker、微软Azure ML各大模型深度分析对比
linux·人工智能·ai·信息安全·云计算·系统运维
述雾学java10 分钟前
深入理解 transforms.Normalize():PyTorch 图像预处理中的关键一步
人工智能·pytorch·python
要努力啊啊啊13 分钟前
使用 Python + SQLAlchemy 创建知识库数据库(SQLite)—— 构建本地知识库系统的基础《一》
数据库·人工智能·python·深度学习·自然语言处理·sqlite
CodeOfCC17 分钟前
c语言 封装跨平台线程头文件
linux·c语言·windows
科文小白狼19 分钟前
Linux下VSCode开发环境配置(LSP)
linux·vscode·里氏替换原则·lsp
Andrew_Xzw1 小时前
数据结构与算法(快速基础C++版)
开发语言·数据结构·c++·python·深度学习·算法
凤头百灵鸟2 小时前
Python语法基础篇(包含类型转换、拷贝、可变对象/不可变对象,函数,拆包,异常,模块,闭包,装饰器)
python