建议收藏,五个Python迷你项目(附源码)("必收藏!5个实用Python迷你项目及源码分享")

原创
ithorizon 6个月前 (10-20) 阅读数 25 #后端开发

必收藏!5个实用Python迷你项目及源码分享

一、简介

Python是一种广泛应用于各种场景的编程语言,其简洁易懂的语法和充裕的库资源使开发者可以迅速实现各种功能。本文将分享5个实用的Python迷你项目,并附上源码,帮助大家更好地学习和掌握Python编程。

二、项目一:猜数字游戏

猜数字游戏是一个非常经典的Python项目,适合初学者入门。下面是项目的基本思路和源码。

import random

def guess_number_game():

number_to_guess = random.randint(1, 100)

attempts = 0

print("欢迎来到猜数字游戏!")

print("我已经想好了一个1到100之间的数字,你能猜到它是多少吗?")

while True:

try:

user_guess = int(input("请输入你猜的数字(1-100):"))

attempts += 1

if user_guess < number_to_guess:

print("太小了,请再试一次。")

elif user_guess > number_to_guess:

print("太大了,请再试一次。")

else:

print(f"恭喜你!你猜对了数字{number_to_guess},你一共猜了{attempts}次。")

break

except ValueError:

print("请输入一个有效的整数。")

if __name__ == "__main__":

guess_number_game()

三、项目二:待办事项列表

待办事项列表可以帮助我们更好地管理日常任务。下面是这个项目的源码。

class TodoList:

def __init__(self):

self.todos = []

def add_todo(self, task):

self.todos.append(task)

print(f"任务'{task}'已添加到待办事项列表。")

def remove_todo(self, task):

if task in self.todos:

self.todos.remove(task)

print(f"任务'{task}'已从待办事项列表中移除。")

else:

print(f"任务'{task}'不在待办事项列表中。")

def show_todos(self):

if self.todos:

print("待办事项列表:")

for task in self.todos:

print(f"- {task}")

else:

print("待办事项列表为空。")

if __name__ == "__main__":

todo_list = TodoList()

while True:

print(" 1. 添加任务")

print("2. 移除任务")

print("3. 显示所有任务")

print("4. 退出")

choice = input("请选择一个操作:")

if choice == "1":

task = input("请输入任务描述:")

todo_list.add_todo(task)

elif choice == "2":

task = input("请输入要移除的任务描述:")

todo_list.remove_todo(task)

elif choice == "3":

todo_list.show_todos()

elif choice == "4":

break

else:

print("无效的操作,请重新选择。")

四、项目三:计算器

计算器是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 "除数不能为0"

else:

return x / y

def calculator():

print("欢迎使用计算器")

print("1. 加法")

print("2. 减法")

print("3. 乘法")

print("4. 除法")

print("5. 退出")

while True:

choice = input("请选择一个操作:")

if choice in ('1', '2', '3', '4'):

num1 = float(input("请输入第一个数字:"))

num2 = float(input("请输入第二个数字:"))

if choice == '1':

print(f"导致是:{add(num1, num2)}")

elif choice == '2':

print(f"导致是:{subtract(num1, num2)}")

elif choice == '3':

print(f"导致是:{multiply(num1, num2)}")

elif choice == '4':

print(f"导致是:{divide(num1, num2)}")

elif choice == '5':

print("感谢使用计算器,再见!")

break

else:

print("无效的操作,请重新选择。")

if __name__ == "__main__":

calculator()

五、项目四:天气查询

天气查询项目可以帮助我们获取指定城市的天气信息。下面是项目的源码。

import requests

def get_weather(city):

api_key = "your_api_key"

base_url = "http://api.openweathermap.org/data/2.5/weather?"

complete_url = f"{base_url}appid={api_key}&q={city}"

response = requests.get(complete_url)

data = response.json()

if data["cod"] != "404":

main = data["main"]

current_temperature = main["temp"]

current_pressure = main["pressure"]

current_humidity = main["humidity"]

weather_description = data["weather"][0]["description"]

print(f"当前{city}的天气:")

print(f"温度:{current_temperature}K")

print(f"气压:{current_pressure}hPa")

print(f"湿度:{current_humidity}%")

print(f"天气状况:{weather_description}")

else:

print("抱歉,没有找到该城市的天气信息。")

if __name__ == "__main__":

city_name = input("请输入城市名:")

get_weather(city_name)

六、项目五:简易爬虫

简易爬虫可以帮助我们获取网页内容。下面是简易爬虫的源码。

import requests

from bs4 import BeautifulSoup

def simple_crawler(url):

response = requests.get(url)

soup = BeautifulSoup(response.text, 'html.parser')

print(f"网页标题:{soup.title.string}")

print("网页链接:")

for link in soup.find_all('a'):

print(link.get('href'))

if __name__ == "__main__":

website_url = input("请输入要爬取的网址:")

simple_crawler(website_url)

七、总结

以上就是五个实用的Python迷你项目及源码分享。这些项目可以帮助我们更好地学习和掌握Python编程,也可以作为我们日常生活中的小工具。期待对大家有所帮助,欢迎收藏和分享!


本文由IT视界版权所有,禁止未经同意的情况下转发

文章标签: 后端开发


热门