30个简单Python项目的轻松解决与解析

你想通过实践来学习 Python 吗?在这篇文章中,我将引导你完成 30 个简单的 Python 项目,提供分步指导和易于理解的说明。你将了解每个项目是如何实现的,以及它为何有用。没有复杂的理论,只有清晰的步骤。让我们开始吧!

你想通过实践来学习 Python 吗?在这篇文章中,我将引导你完成 30 个简单的 Python 项目,提供分步指导和易于理解的说明。你将了解每个项目是如何实现的,以及它为何有用。没有复杂的理论,只有清晰的步骤。让我们开始吧!

持续练习。从一些简单、规模较小且易于上手的项目开始,比如计算器或待办事项列表,这样你可以逐渐适应编程。

1. 填空游戏

用单词填空,生成搞笑句子。你将学习如何从用户处获取输入并显示结果。

print("Enter words for a fun story!")
noun = input("Noun: ")
verb = input("Verb: ")
place = input("Place: ")
print(f"One day, a {noun} decided to {verb} at the {place}.")
元素周期表

2. 猜数字

计算机选择一个数字,你来猜。你将学习随机数、循环以及如何判断猜测是否过高或过低。

import random

number = random.randint(1, 10)
guess = int(input("Guess a number between 1 and 10: "))

while guess != number:
    if guess < number:
        print("Too low!")
    else:
        print("Too high!")
    guess = int(input("Try again: "))

print("You got it!")

3. 剪刀石头布

与电脑对战这款70年代经典游戏。练习随机性、决策和显示结果。

import random
choices = ["rock", "paper", "scissors"]
user = input("Choose rock, paper or scissors: ").lower()
computer = random.choice(choices)
print(f"Computer chose: {computer}")
if user == computer:
    print("It's a tie!")
elif (user == "rock" and computer == "scissors") or \
     (user == "paper" and computer == "rock") or \
     (user == "scissors" and computer == "paper"):
    print("You win!")
else:
    print("You lose!")

4. 猜字游戏

在用尽尝试次数前猜出单词。你将使用列表、条件语句,并跟踪已使用过的字母。

word = "apple"
guessed = ["_"] * len(word)
tries = 5
while tries > 0 and "_" in guessed:
    guess = input("Guess a letter: ").lower()
    if guess in word:
        for i in range(len(word)):
            if word[i] == guess:
                guessed[i] = guess
    else:
        tries -= 1
    print(" ".join(guessed))
if "_" not in guessed:
    print("You win!")
else:
    print("You lose! Word was:", word)

5. 倒计时器

输入你希望等待的大致秒数,然后观看倒计时器出现。学习循环和延迟。

import time
secs = int(input("Enter seconds: "))
while secs:
    print(secs)
    time.sleep(1)
    secs -= 1
print("Time's up!")

6. 密码生成器

生成随机且安全的密码。你将使用循环、对字符串进行计算,并使用Python中的随机函数。

import random
import string
length = int(input("Password length: "))
chars = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(chars) for _ in range(length))
print("Your password:", password)

7. 二维码生成器/扫描器

将文本转换为二维码或从二维码中读取数据。您将掌握库函数,实现文本与图像的双向转换。

import qrcode
data = input("Enter text for QR code: ")
img = qrcode.make(data)
img.save("qrcode.png")
print("QR code saved as qrcode.png")

8. 井字游戏(双人模式)

与朋友一起玩3×3版本的游戏。你尝试绘制网格、请求轮次并检查胜者。

board = [" "] * 9
def show():
    print(f"{board[0]}|{board[1]}|{board[2]}")
    print(f"{board[3]}|{board[4]}|{board[5]}")
    print(f"{board[6]}|{board[7]}|{board[8]}")
player = "X"
for _ in range(9):
    show()
    move = int(input(f"{player}'s turn (0-8): "))
    if board[move] == " ":
        board[move] = player
        player = "O" if player == "X" else "X"
show()
print("Game Over")

9. 井字游戏对战电脑

相同的游戏,但由电脑来玩。你将了解最小最大法概念(适用于小型游戏)。

10. 二分搜索工具

给定一个排序列表,查找一个数字。你将练习将列表划分为部分——这是学习如何巧妙思考的简单方法。

def binary_search(arr, target):
    low, high = 0, len(arr)-1
    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1

numbers = [1, 3, 5, 7, 9, 11]
target = int(input("Enter number to search: "))
index = binary_search(numbers, target)
print("Found at index:", index if index != -1 else "Not found")

11. 扫雷(文本版本)

经典扫雷游戏,你需要避开地雷。你将进一步了解循环、映射和单元格检查。

board = [[" " for _ in range(5)] for _ in range(5)]
mines = [(1, 1), (2, 3)]
for x, y in mines:
    board[x][y] = "*"

for row in board:
    print(" ".join(row))

12. 数独解谜器

输入数独棋盘,程序自动解谜。你将学习如何回溯并进行逻辑推导。

def is_valid(board, row, col, num):
    for i in range(9):
        if board[row][i] == num or board[i][col] == num:
            return False
    x, y = 3*(row//3), 3*(col//3)
    for i in range(x, x+3):
        for j in range(y, y+3):
            if board[i][j] == num:
                return False
    return True

def solve(board):
    for r in range(9):
        for c in range(9):
            if board[r][c] == 0:
                for num in range(1, 10):
                    if is_valid(board, r, c, num):
                        board[r][c] = num
                        if solve(board):
                            return True
                        board[r][c] = 0
                return False
    return True

13. 简单图像滤镜

调整亮度或为图像添加模糊效果。这里使用了Pillow库。

from PIL import Image, ImageFilter
img = Image.open("image.jpg")
blur = img.filter(ImageFilter.BLUR)
blur.save("blurred.jpg")

14. 马尔可夫文本生成器

使用规则生成有趣的文本。这让你了解基于真实文本模式的初级人工智能如何运作。

import random
text = "hello there hello world"
words = text.split()
pairs = {}
for i in range(len(words)-1):
    if words[i] not in pairs:
        pairs[words[i]] = []
    pairs[words[i]].append(words[i+1])

word = random.choice(words)
for _ in range(10):
    print(word, end=" ")
    word = random.choice(pairs.get(word, words))

15. 乒乓球游戏(Pygame)

一个简单的双拍球游戏。你将学习游戏循环、绘制形状和处理用户输入。

import pygame
pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption("Pong")
clock = pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
    screen.fill((0, 0, 0))
    pygame.display.flip()
    clock.tick(60)

16. 贪吃蛇游戏

操控一条不断增长的蛇吞食食物。你将熟悉Pygame、速度控制和地图更新机制。

import pygame, random, sys
pygame.init()
size = 300
cell = 10
screen = pygame.display.set_mode((size, size))
clock = pygame.time.Clock()

x = y = 150
dx = cell
dy = 0
snake = [(x, y)]
food = (random.randint(0, 29)*10, random.randint(0, 29)*10)

while True:
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            pygame.quit(); sys.exit()
        elif e.type == pygame.KEYDOWN:
            if e.key == pygame.K_UP: dx, dy = 0, -cell
            elif e.key == pygame.K_DOWN: dx, dy = 0, cell
            elif e.key == pygame.K_LEFT: dx, dy = -cell, 0
            elif e.key == pygame.K_RIGHT: dx, dy = cell, 0

    x += dx
    y += dy
    snake.insert(0, (x, y))
    if (x, y) == food:
        food = (random.randint(0, 29)*10, random.randint(0, 29)*10)
    else:
        snake.pop()

    if x < 0 or x >= size or y < 0 or y >= size or (x, y) in snake[1:]:
        pygame.quit(); sys.exit()

    screen.fill((0, 0, 0))
    for s in snake:
        pygame.draw.rect(screen, (0, 255, 0), (*s, cell, cell))
    pygame.draw.rect(screen, (255, 0, 0), (*food, cell, cell))
    pygame.display.update()
    clock.tick(10)

17. 四子棋游戏

在列中放置棋子以形成四子连线。你将深入学习逻辑、循环和胜负判定。

board = [[" "]*7 for _ in range(6)]

def print_board():
    for row in board:
        print("|".join(row))
    print("-" * 13)

def drop(col, player):
    for row in reversed(board):
        if row[col] == " ":
            row[col] = player
            return True
    return False

turn = "X"
while True:
    print_board()
    col = int(input(f"{turn}'s turn (0–6): "))
    if 0 <= col < 7 and drop(col, turn):
        turn = "O" if turn == "X" else "X"

18. 俄罗斯方块游戏

方块下落,你需将其排列成行。你将学习图形、碰撞检测及使用pygame处理形状。

# Just a placeholder. Real Tetris takes ~300 lines.
print("Making a full Tetris game in Python takes many steps.")
print("Use 'pygame' and search: 'Simple Tetris Pygame Tutorial' for full code.")

19. 在线多人游戏

通过网络进行游戏。你将学习套接字、如何在互联网上发送和接收消息。

服务器

import socket
s = socket.socket()
s.bind(('localhost', 1234))
s.listen(1)
print("Waiting for connection...")
conn, addr = s.accept()
print("Connected:", addr)
while True:
    data = conn.recv(1024).decode()
    if not data: break
    print("Client:", data)
    conn.send(data.encode())

客户端

import socket
s = socket.socket()
s.connect(('localhost', 1234))
while True:
    msg = input("You: ")
    s.send(msg.encode())
    data = s.recv(1024).decode()
    print("Server:", data)

20. 网页抓取工具

输入网站链接,它会为你提取文本或链接。你将学习BeautifulSoup和简单的网页解析。

import requests
from bs4 import BeautifulSoup

url = input("Enter website URL: ")
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')

for link in soup.find_all('a'):
    print(link.get('href'))

21. 批量文件重命名工具

选择一个文件夹,并以特定格式重命名所有文件。你将学会轻松处理文件夹和文件。

import os
folder = input("Enter folder path: ")
new_name = input("New name (e.g. file_): ")

for i, filename in enumerate(os.listdir(folder)):
    ext = filename.split('.')[-1]
    os.rename(
        os.path.join(folder, filename),
        os.path.join(folder, f"{new_name}{i}.{ext}")
    )
print("Files renamed.")

22. 天气应用

输入一个城市,它将告诉你该地的天气。你将学会如何查询API服务并获取JSON格式的结果。

import requests

city = input("Enter city: ")
url = f"http://wttr.in/{city}?format=3"
r = requests.get(url)
print("Weather:", r.text)

23. Discord 机器人

一个用于创建 Discord 聊天机器人的工具。你将学习如何与 API 互动,如何“监听”消息以及如何“回复”消息。

# Save as bot.py
import discord

client = discord.Client()

@client.event
async def on_ready():
    print("Bot is ready!")

@client.event
async def on_message(message):
    if message.content == "!hello":
        await message.channel.send("Hello!")

client.run("YOUR_BOT_TOKEN")

24. 空间入侵者游戏

经典射击游戏,包含敌方行。你所学的大部分内容来自pygame——关于循环、子弹和碰撞。

# Full game too long for here.
print("To build this, use Pygame. Search: 'Python Space Invaders pygame tutorial'")

25. 斐波那契计算器

输入一个数字,获取其斐波那契输出。你将掌握递归和函数的使用。

def fib(n):
    a, b = 0, 1
    for _ in range(n):
        print(a, end=' ')
        a, b = b, a + b

n = int(input("Enter how many numbers: "))
fib(n)

26. YouTube 视频下载器

输入链接即可下载视频。你将依赖库文件完成核心功能。

from pytube import YouTube

url = input("Enter YouTube URL: ")
yt = YouTube(url)
yt.streams.get_highest_resolution().download()
print("Video downloaded.")

27. 闹钟图形界面

设计一个在指定时间发出声音的闹钟。你将学习 Tkinter 和闹钟功能。

import time
alarm_time = input("Set alarm (HH:MM): ")
while True:
    now = time.strftime("%H:%M")
    if now == alarm_time:
        print("Time to wake up!")
        break
    time.sleep(10)

28. 桌面通知器

显示小型弹出提示。你将学习系统消息和简单提示的实现。

from plyer import notification

notification.notify(
    title="Reminder",
    message="Take a short break!",
    timeout=5
)

29. 语音转文本

对着麦克风说话,屏幕上显示文字。你将学习使用语音工具并处理音频。

import speech_recognition as sr

rec = sr.Recognizer()
with sr.Microphone() as source:
    print("Speak something...")
    audio = rec.listen(source)
    text = rec.recognize_google(audio)
    print("You said:", text)

30. 货币转换器

输入一个金额,即可将其转换为另一种货币。你将学习API的工作原理,以及如何创建用于转换的矩阵。

import requests

amount = float(input("Amount in USD: "))
r = requests.get("https://api.exchangerate-api.com/v4/latest/USD")
rates = r.json()['rates']
currency = input("Convert to (e.g. INR): ").upper()

if currency in rates:
    print(f"{amount} USD = {amount * rates[currency]:.2f} {currency}")
else:
    print("Currency not found.")

这些项目为何重要

每个项目都能提升你的技能:用户输入、循环、决策、文件、图像、游戏、API。你在实践中学习,并逐渐意识到 Python 能够实现许多功能。

开始任何项目的简单步骤

  1. 明确项目功能(例如:从 n 倒计时到 0)。
  2. 确定需要编写的代码(例如:忘记导入循环和时间模块)。
  3. 编写部分代码并进行测试。
  4. 解决小问题。
  5. 尝试添加一个小功能:比如输出颜色,或保存结果。

结语

感谢您阅读全文!希望您已准备好独立完成这30个简单的Python项目。如果您喜欢这篇文章,请点赞、留言并分享。如果您需要更多类似的内容,可以阅读我的一些旧文章,其中充满了有趣的项目和简单的指南。

祝编程愉快! 💻

元素周期表抱枕

你也许感兴趣的:

共有{2}精彩评论

  1. yz 对这篇文章的反应是赞一个
  2. Upon reflection, I felt like your article was and not keeping
    your head stuck in the phone the whole while, either) and living a life with appreciation for the natural world, helps people feel grounded.

    Philosophizing about important memes is likewise some other sort of experience that can help us know ourselves.

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注