进行Python基础项目实践是学习和掌握Python编程的一个非常有效的方法。以下是一些适合初学者的小项目实践,旨在帮助你熟悉Python的基本语法和常见库。
1. 计算器
创建一个简单的命令行计算器,可以执行基本的算术运算(加、减、乘、除)。
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return "Error! Division by zero."
return x / y
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input("Enter choice(1/2/3/4): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(f"{
num1} + {
num2} = {
add(num1, num2)}")
elif choice == '2':
print(f"{
num1} - {
num2} = {
subtract(num1, num2)}")
elif choice == '3':
print(f"{
num1} * {
num2} = {
multiply(num1, num2)}")
elif choice == '4':
print(f"{
num1} / {
num2} = {
divide(num1, num2)}")
else:
print("Invalid Input")
2. 天气预报应用
使用OpenWeatherMap API来获取特定城市的天气信息。
步骤:
- 注册一个OpenWeatherMap账户并获取API密钥。
- 使用
requests
库来发送HTTP请求。 - 解析返回的JSON数据并显示天气信息。
import requests
def get_weather(city, api_key):
url = f"http://api.openweathermap.org/data/2.5/weather?q={
city}&appid={
api_key}&units=metric"
response = requests.get(url)
data = response.json()
if response.status_code == 200:
main = data['main']
weather = data['weather'][0]
print(f"City: {
city}")
print(f"Temperature: {
main['temp']}°C")
print(f"Humidity: {
main['humidity']}%")
print(f"Weather: {
weather['description']}")
else:
print("Error in the HTTP request")
api_key = "YOUR_API_KEY"
city = input("Enter city name: ")
get_weather(city, api_key)
3. 简单的Web爬虫
编写一个简单的网页爬虫,从指定网页中提取特定信息(如标题、链接等)。
import requests
from bs4 import BeautifulSoup
def fetch_webpage(url):
response = requests.get(url)
if response.status_code == 200:
return response.text
else:
return None
def parse_webpage(html_content):
soup = BeautifulSoup(html_content, 'html.parser')
title = soup.title.string if soup.title else "No Title"
links = [a.get('href') for a in soup.find_all('a', href=True)]
return title, links
url = input("Enter URL: ")
html_content = fetch_webpage(url)
if html_content:
title, links = parse_webpage(html_content)
print(f"Title: {
title}")
print("Links:")
for link in links:
print(link)
else:
print("Failed to fetch webpage")
4. To-Do List应用
创建一个简单的命令行To-Do List应用,允许用户添加、查看和删除任务。
import json
def load_tasks():
try:
with open('tasks.json', 'r') as file:
tasks = json.load(file)
except FileNotFoundError:
tasks = []
return tasks
def save_tasks(tasks):
with open('tasks.json', 'w') as file:
json.dump(tasks, file, indent=4)
def add_task(tasks):
task = input("Enter task: ")
tasks.append(task)
save_tasks(tasks)
print("Task added!")
def view_tasks(tasks):
if not tasks:
print("No tasks to show.")
else:
for i, task in enumerate(tasks, start=1):
print(f"{
i}. {
task}")
def delete_task(tasks):
view_tasks(tasks)
try:
choice = int(input("Enter task number to delete: "))
if 1 <= choice <= len(tasks):
tasks.pop(choice - 1)
save_tasks(tasks)
print("Task deleted!")
else:
print("Invalid choice.")
except ValueError:
print("Invalid input.")
def main():
tasks = load_tasks()
while True:
print("\n1. Add Task")
print("2. View Tasks")
print("3. Delete Task")
print("4. Exit")
choice = input("Enter choice: ")
if choice == '1':
add_task(tasks)
elif choice == '2':
view_tasks(tasks)
elif choice == '3':
delete_task(tasks)
elif choice == '4':
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
5. 简单文件加密和解密
编写一个简单的Python脚本来加密和解密文本文件。
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
import base64
def encrypt_file(file_path, key):
cipher = AES.new(key, AES.MODE_CBC)
ct_bytes = cipher.encrypt(pad(open(file_path, "rb").read(), AES.block_size))
iv = base64.b64encode(cipher.iv).decode('utf-8')
ct = base64.b64encode(ct_bytes).decode('utf-8')
with open(file_path + ".enc", "w") as f:
f.write(f"{
iv}:{
ct}")
def decrypt_file(file_path, key):
with open(file_path, "r") as f:
iv, ct = f.read().split(':')
iv = base64.b64decode(iv)
ct = base64.b64decode(ct)
cipher = AES.new(key, AES.MODE_CBC, iv)
pt = unpad(cipher.decrypt(ct), AES.block_size)
with open(file_path.replace(".enc", ""), "wb") as f:
f.write(pt)
key = get_random_bytes(16) # Use a secure method to generate a key in a real-world scenario
file_path = input("Enter file path: ")
choice = input("Encrypt (e) or Decrypt (d)? ").lower()
if choice == 'e':
encrypt_file(file_path, key)
elif choice == 'd':
decrypt_file(file_path, key)
else:
print("Invalid choice")
注意:在使用加密功能时,确保安装了pycryptodome
库(可以使用pip install pycryptodome
来安装)。
这些项目可以帮助你巩固Python基础知识,并且可以根据需要进一步扩展。通过实际动手编写代码,你会更好地理解Python的编程范式和常用库的使用方法。