有趣python代码

生成彩虹:在终端上显示彩虹。

python
import colorama import time colorama.init() colors = [ colorama.Fore.RED, colorama.Fore.YELLOW, colorama.Fore.GREEN, colorama.Fore.BLUE, colorama.Fore.MAGENTA, colorama.Fore.CYAN, colorama.Fore.WHITE ] text = "Hello, Rainbow!" for color in colors: print(color + text) time.sleep(0.5) colorama.deinit()

文字动画:让文字在终端上移动。

python
import sys import time def print_loading_bar(): for i in range(20): sys.stdout.write('\r') sys.stdout.write("[%-20s] %d%%" % ('=' * i, 5 * i)) sys.stdout.flush() time.sleep(0.1) print_loading_bar() print("\nLoading complete!")

文本进度条:在终端上显示进度条。

python
import sys import time def print_progress_bar(iteration, total, length=50, fill='█'): percent = ("{0:.1f}").format(100 * (iteration / float(total))) filled_length = int(length * iteration // total) bar = fill * filled_length + '-' * (length - filled_length) sys.stdout.write('\r |%s| %s%% Complete' % (bar, percent)) sys.stdout.flush() # 示例用法 total = 100 for i in range(total + 1): time.sleep(0.1) print_progress_bar(i, total)

谜题解决器:使用 Python 解决数独谜题。

python
def print_board(board): for i in range(9): for j in range(9): print(board[i][j], end=" ") print() def is_safe(board, row, col, num): for x in range(9): if board[row][x] == num or board[x][col] == num or board[row - row % 3 + x // 3][col - col % 3 + x % 3] == num: return False return True def solve_sudoku(board): for i in range(9): for j in range(9): if board[i][j] == 0: for num in range(1, 10): if is_safe(board, i, j, num): board[i][j] = num if solve_sudoku(board): return True board[i][j] = 0 return False return True # 使用一个未解决的数独谜题作为输入 sudoku_board = [ [5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9] ] if solve_sudoku(sudoku_board): print_board(sudoku_board) else: print("No solution exists.")

这些代码片段只是冰山一角,Python 的强大之处在于它的灵活性,你可以用它做很多有趣的事情。

ASCII 艺术生成器:将文本转换成 ASCII 艺术。

python
from pyfiglet import Figlet def generate_ascii_art(text, font="standard"): f = Figlet(font=font) ascii_art = f.renderText(text) print(ascii_art) generate_ascii_art("Hello, ASCII Art!")

你需要安装 pyfiglet 库,可以使用

bash
pip install pyfiglet

猜数字游戏:简单的猜数字游戏。

python
import random def guess_the_number(): number_to_guess = random.randint(1, 100) attempts = 0 while True: guess = int(input("Guess the number (between 1 and 100): ")) attempts += 1 if guess == number_to_guess: print(f"Congratulations! You guessed the number in {attempts} attempts.") break elif guess < number_to_guess: print("Too low. Try again.") else: print("Too high. Try again.") guess_the_number()

网络爬虫:使用 BeautifulSoup 库从网页中抓取信息。

python
import requests from bs4 import BeautifulSoup def get_wikipedia_intro(query): url = f"https://en.wikipedia.org/wiki/{query}" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") intro = soup.find("p").get_text() print(intro) get_wikipedia_intro("Python_(programming_language)")

确保你已经安装了 beautifulsoup4requests

bash
pip install beautifulsoup4 requests

标签