好玩的python代码示例
当涉及到编写有趣的Python代码示例时,只有想象力是您的极限。彩虹输出:在终端中输出彩虹文字。
pythonimport colorama
from colorama import Fore, Back, Style
import time
colorama.init()
colors = [Fore.RED, Fore.YELLOW, Fore.GREEN, Fore.BLUE, Fore.MAGENTA, Fore.CYAN]
text = "Hello, Rainbow!"
for char, color in zip(text, colors * (len(text) // len(colors) + 1)):
print(color + char, end="")
time.sleep(0.1)
print(Style.RESET_ALL)
谷歌搜索:通过Python脚本在终端中进行谷歌搜索。
pythonimport webbrowser
search_query = input("Enter your Google search: ")
url = f"https://www.google.com/search?q={search_query}"
webbrowser.open(url)
数字迷宫:生成一个数字迷宫,然后使用递归函数找到路径。
pythonimport random
def generate_maze(size):
return [[random.choice([0, 1]) for _ in range(size)] for _ in range(size)]
def display_maze(maze):
for row in maze:
print(" ".join(map(str, row)))
def solve_maze(maze, x, y):
if 0 <= x < len(maze) and 0 <= y < len(maze) and maze[x][y] == 1:
maze[x][y] = 9 # Mark the path
display_maze(maze)
print("\n")
solve_maze(maze, x + 1, y) # Down
solve_maze(maze, x, y + 1) # Right
solve_maze(maze, x - 1, y) # Up
solve_maze(maze, x, y - 1) # Left
maze_size = 5
maze = generate_maze(maze_size)
display_maze(maze)
print("\nSolving maze:\n")
solve_maze(maze, 0, 0)
文字动画:使用ASCII艺术创建一个简单的文字动画。
pythonimport time
import os
def clear_screen():
os.system('cls' if os.name == 'nt' else 'clear')
def text_animation(text):
frames = [f"Frame {i}: {text}" for i in range(1, 6)]
for frame in frames:
clear_screen()
print(frame)
time.sleep(0.5)
text_animation("Hello, ASCII Art!")
随机密码生成器:生成一个随机密码,包括字母、数字和特殊字符。
pythonimport random
import string
def generate_random_password(length=12):
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for _ in range(length))
return password
random_password = generate_random_password()
print(f"Random Password: {random_password}")
倒计时器:创建一个简单的倒计时器,让用户输入倒计时时间。
pythonimport time
def countdown_timer(seconds):
while seconds:
mins, secs = divmod(seconds, 60)
timeformat = '{:02d}:{:02d}'.format(mins, secs)
print(timeformat, end='\r')
time.sleep(1)
seconds -= 1
print("Time's up!")
user_input = int(input("Enter the countdown time in seconds: "))
countdown_timer(user_input)