建议收藏,五个Python迷你项目(附源码)("Python学习必备:五个实用迷你项目推荐(附完整源码下载)")
原创
一、引言
Python作为一种流行的编程语言,其简洁的语法和强盛的功能深受开发者喜爱。在学习Python的过程中,实践是最好的学习方法。本文将推荐五个实用的Python迷你项目,帮助大家巩固Python知识,尽大概缩减损耗编程技能。以下是五个项目的简要介绍及源码下载链接。
二、项目一:计算器
本项目实现了一个易懂的计算器,可以完成加、减、乘、除等基本运算。以下是项目源码:
# 计算器项目源码
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."
else:
return x / y
while True:
print("Options:")
print("Enter 'add' for addition")
print("Enter 'subtract' for subtraction")
print("Enter 'multiply' for multiplication")
print("Enter 'divide' for division")
print("Enter 'quit' to end the program")
user_input = input(": ")
if user_input == "quit":
break
elif user_input in ('add', 'subtract', 'multiply', 'divide'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if user_input == 'add':
print("The result is:", add(num1, num2))
elif user_input == 'subtract':
print("The result is:", subtract(num1, num2))
elif user_input == 'multiply':
print("The result is:", multiply(num1, num2))
elif user_input == 'divide':
print("The result is:", divide(num1, num2))
else:
print("Unknown command")
三、项目二:待办事项列表
本项目实现了一个待办事项列表,用户可以添加、删除和查看待办事项。以下是项目源码:
# 待办事项列表项目源码
todo_list = []
def add_todo():
todo = input("Enter a new todo item: ")
todo_list.append(todo)
print(f"Added '{todo}' to the todo list.")
def remove_todo():
todo = input("Enter the todo item to remove: ")
if todo in todo_list:
todo_list.remove(todo)
print(f"Removed '{todo}' from the todo list.")
else:
print("Item not found in the todo list.")
def view_todo():
if len(todo_list) == 0:
print("The todo list is empty.")
else:
print("Todo List:")
for index, item in enumerate(todo_list, start=1):
print(f"{index}. {item}")
while True:
print(" Todo List Menu")
print("1. Add a todo item")
print("2. Remove a todo item")
print("3. View the todo list")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == "1":
add_todo()
elif choice == "2":
remove_todo()
elif choice == "3":
view_todo()
elif choice == "4":
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a number between 1 and 4.")
四、项目三:猜数字游戏
本项目实现了一个猜数字游戏,程序会随机生成一个1到100之间的整数,用户需要猜测这个数字。以下是项目源码:
# 猜数字游戏项目源码
import random
def guess_number():
number_to_guess = random.randint(1, 100)
attempts = 0
print("Guess the number between 1 and 100.")
while True:
try:
user_guess = int(input("Enter your guess: "))
attempts += 1
if user_guess == number_to_guess:
print(f"Congratulations! You guessed the right number in {attempts} attempts.")
break
elif user_guess < number_to_guess:
print("Try again! The number is higher.")
else:
print("Try again! The number is lower.")
except ValueError:
print("Please enter a valid integer.")
guess_number()
五、项目四:数据可视化
本项目使用Python的matplotlib库实现数据可视化,绘制了易懂的折线图、柱状图和饼图。以下是项目源码:
# 数据可视化项目源码
import matplotlib.pyplot as plt
# 折线图
def plot_line_chart():
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.plot(x, y)
plt.title("Line Chart")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
# 柱状图
def plot_bar_chart():
x = ['A', 'B', 'C', 'D']
y = [10, 15, 7, 10]
plt.bar(x, y)
plt.title("Bar Chart")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
# 饼图
def plot_pie_chart():
labels = 'A', 'B', 'C', 'D'
sizes = [15, 30, 45, 10]
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=140)
plt.axis('equal')
plt.show()
plot_line_chart()
plot_bar_chart()
plot_pie_chart()
六、项目五:简易Web服务器
本项目使用Python的http.server模块实现了一个简易的Web服务器,可以浏览本地静态文件。以下是项目源码:
# 简易Web服务器项目源码
import http.server
import socketserver
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print(f"Serving at port {PORT}")
httpd.serve_forever()
七、总结
本文介绍了五个实用的Python迷你项目,包括计算器、待办事项列表、猜数字游戏、数据可视化和简易Web服务器。这些项目可以帮助初学者巩固Python基础知识,尽大概缩减损耗编程能力。建议读者动手实践这些项目,并在实践中逐步学习和进步。