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)

结果

相关推荐
冰橙子id38 分钟前
linux-远程访问管理(sshd,scp,sftp)
linux·网络·ssh
光电的一只菜鸡2 小时前
ubuntu之坑(十五)——设备树
linux·数据库·ubuntu
橡晟3 小时前
深度学习入门:让神经网络变得“深不可测“⚡(二)
人工智能·python·深度学习·机器学习·计算机视觉
墨尘游子3 小时前
神经网络的层与块
人工智能·python·深度学习·机器学习
倔强青铜33 小时前
苦练Python第18天:Python异常处理锦囊
开发语言·python
saynaihe3 小时前
ubuntu 22.04 anaconda comfyui安装
linux·运维·服务器·ubuntu
企鹅与蟒蛇4 小时前
Ubuntu-25.04 Wayland桌面环境安装Anaconda3之后无法启动anaconda-navigator问题解决
linux·运维·python·ubuntu·anaconda
小蜜蜂爱编程4 小时前
ubuntu透网方案
运维·服务器·ubuntu
autobaba4 小时前
编写bat文件自动打开chrome浏览器,并通过selenium抓取浏览器操作chrome
chrome·python·selenium·rpa
程序设计实验室4 小时前
小心误关了NAS服务器!修改Linux的电源键功能
linux·nas