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)

结果

相关推荐
rayyy95 小时前
Linux 下标准的 libX.so 软链接生成
linux
unicrom_深圳市由你创科技5 小时前
上位机开发常用的语言 / 框架有哪些?
c++·python·c#
实心儿儿6 小时前
Linux —— 基础IO - 文件描述符
linux·运维·服务器
clear sky .6 小时前
[linux]视频实时推流项目
linux·服务器·音视频
abc123456sdggfd6 小时前
bootstrap如何修改输入框获取焦点时的光晕
jvm·数据库·python
qq_330037996 小时前
如何配置ASM元数据备份_md_backup与md_restore重建磁盘组结构
jvm·数据库·python
昭昭日月明6 小时前
前端仔速通 Python
javascript·python
RisunJan6 小时前
Linux命令-nisdomainname(显示或设置系统的 NIS(Network Information Service)域名)
linux·运维·服务器
a9511416426 小时前
SQL触发器实现自动生成流水号_配合序列对象实现递增逻辑
jvm·数据库·python
哦哦~9216 小时前
FDTD 与 Python 联合仿真的超表面智能设计技术与应用
python·fdtd·超表面