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)

结果

相关推荐
驱动探索者5 分钟前
Linux list 设计
linux·运维·list
遇见火星17 分钟前
在Linux中使用parted对大容量磁盘进行分区详细过程
linux·运维·网络·分区·parted
yuyousheng27 分钟前
CentOS7更换为阿里源
linux·c语言
给你一页白纸28 分钟前
将分散的Pytest测试脚本统一接入测试平台:FastAPI改造方案详解
python·pytest·接口自动化·测试平台
孤狼warrior34 分钟前
图像生成 Stable Diffusion模型架构介绍及使用代码 附数据集批量获取
人工智能·python·深度学习·stable diffusion·cnn·transformer·stablediffusion
大哥手下留情43 分钟前
Python火车票查询方法介绍
开发语言·python
努力毕业的小土博^_^1 小时前
【AI课程领学】第十二课 · 超参数设定与网络训练(课时1) 网络超参数设定:从“要调什么”到“怎么系统地调”(含 PyTorch 可复用模板)
人工智能·pytorch·python·深度学习·神经网络·机器学习
微露清风1 小时前
系统性学习Linux-第一讲-Linux基础指令
java·linux·学习
YMLT花岗岩1 小时前
Python学习之-函数-入门训练-在函数中修改全局变量
python·学习
花月mmc1 小时前
CanMV K230 波形识别——数据分析(2)
python·数据挖掘·数据分析·信号处理