python比较炫酷的代码
以下是一些比较炫酷的Python代码示例:
生成彩色文本
class colors:
reset='3[0m'
bold='3[01m'
disable='3[02m'
underline='3[04m'
reverse='3[07m'
strikethrough='3[09m'
invisible='3[08m'
class fg:
black='3[30m'
red='3[31m'
green='3[32m'
orange='3[33m'
blue='3[34m'
purple='3[35m'
cyan='3[36m'
lightgrey='3[37m'
darkgrey='3[90m'
lightred='3[91m'
lightgreen='3[92m'
yellow='3[93m'
lightblue='3[94m'
pink='3[95m'
lightcyan='3[96m'
class bg:
black='3[40m'
red='3[41m'
green='3[42m'
orange='3[43m'
blue='3[44m'
purple='3[45m'
cyan='3[46m'
lightgrey='3[47m'
print(colors.fg.red + "Hello, World!" + colors.reset)
生成随机密码
import random
import string
def generate_password(length):
letters = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(letters) for i in range(length))
print(generate_password(10))
生成ASCII艺术
print(r"""
__ __ ______ ______ __ __ ______ ______
/\ \_\ \ /\ __ \ /\ ___\ /\ \/ / /\ ___\ /\ ___\
\ \ __ \ \ \ __ \ \ \___ \ \ \ _"-. \ \ __\ \ \___ \
\ \_\ \_\ \ \_\ \_\ \/\_____\ \ \_\ \_\ \ \_____\ \/\_____\
\/_/\/_/ \/_/\/_/ \/_____/ \/_/\/_/ \/_____/ \/_____/
""")
生成动态进度条
import time
def progress_bar(total):
for i in range(total):
time.sleep(0.1)
print('\r' + '[' + '='*i + '>' + ' '*(total-i-1) + ']' + f' {i+1}/{total}', end='')
progress_bar(50)
生成迷宫
import random
def generate_maze(width, height):
maze = [['#']*width + ['#'] for _ in range(height)] + [['#']*(width+1)]
visited = [[False]*width + [True] for _ in range(height)] + [[True]*(width+1)]
vertical = [['|']*width + [''] for _ in range(height)] + [[]]
horizontal = [['-']*(width+1) for _ in range(height)] + [[]]
def walk(x, y):
visited[y][x] = True
directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
random.shuffle(directions)
for dx, dy in directions:
nx, ny = x+dx, y+dy
if visited[ny][nx]:
continue
if dx == 1:
horizontal[y][x+1] = '-'
elif dx == -1:
horizontal[ny][nx+1] = '-'
elif dy == 1:
vertical[y+1][x] = '|'
elif dy == -1:
vertical[ny+1][nx] = '|'
walk(nx, ny)
walk(random.randrange(width), random.randrange(height))
maze_str = ''
for i in range(height+1):
maze_str += ''.join(horizontal[i] + ['\n'] + vertic_