前言
随着 Python 语言的流行,越来越多的人加入到了 Python 的大家庭中。到底为什么这么多人学 Python ?我要喊出那句话了:“人生苦短,我用 Python!”,正是因为语法简单、容易学习,所以 Python 深受大家喜爱。(Python!Python!Python!)
Python 初学者在迈过安装编程环境和基本语法的门槛 ,准备大展身手的时候,可能突然就会进入迷茫期:不知道做些什么、再学些什么。然后对编程的兴趣就会慢慢消退,找不到坚持下去的理由,从而慢慢淡忘之前学会的编程知识。
所以找到自己感兴趣、能够跟着动手和学习的 Python 项目是特别重要的,这样才能把学会的 Python 知识用起来,不断地提高。最终从新手晋升为高手!
不管学习哪门语言都希望能做出实际的东西来,这个实际的东西当然就是项目啦,不用多说大家都知道学编程语言一定要做项目才行。
有很多朋友问我学习了Python后,有没有什么好的项目可以练手。
其实,做项目主要还是根据需求来的。但是对于一个初学者来说,很多复杂的项目没办法独立完成,因此博主挑选了一些非常适合初学者的项目,内容不是很复杂,但是非常有趣,我相信对于初学者小白来说是再好不过的项目了。
这里整理了30个精品的Python实战项目列表,都有完整且详细的教程,你可以从中选择自己想做的项目进行参考学习练手,你也可以从中寻找灵感去做自己的项目。
【----相关技术讨论,Python入门基础教程文末见晓!----】
一、自动发送邮件
用Python编写一个可以发送电子邮件的脚本。
提示:email库可用于发送电子邮件。
import smtplib
from email.message import EmailMessage
email = EmailMessage()
## Creating a object for EmailMessage
email['from'] = 'xyz name'
## Person who is sending
email['to'] = 'xyz id'
## Whom we are sending
email['subject'] = 'xyz subject'
## Subject of email
email.set_content("Xyz content of email")
## content of email
with smtlib.SMTP(host='smtp.gmail.com',port=587)as smtp:
## sending request to server
smtp.ehlo()
## server object
smtp.starttls()
## used to send data between server and client
smtp.login("email_id","Password")
## login id and password of gmail
smtp.send_message(email)
## Sending email
print("email send")
## Printing success message
二、Hangman(猜单词的游戏)
用Python创建一个简单的hangman猜单词游戏。
提示:创建一个密码词的列表并随机选择一个单词。将每个单词用下划线“”表示,让用户猜单词,如果用户猜对了,则将用单词替换掉“”。
import time import random name = input("What is your name? ")
print ("Hello, " + name, "Time to play hangman!")
time.sleep(1) print ("Start guessing...\n")
time.sleep(0.5)
## A List Of Secret Words
words = ['python','programming','treasure','creative','medium','horror']
word = random.choice(words)
guesses = ''
turns = 5
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print (char,end="")
else:
print ("_",end=""),
failed += 1
if failed == 0:
print ("\nYou won")
break
guess = input("\nguess a character:")
guesses += guess
if guess not in word:
turns -= 1
print("\nWrong")
print("\nYou have", + turns, 'more guesses')
if turns == 0:
print ("\nYou Lose")`
三、闹钟
用Python编写一个创建闹钟的脚本。
提示:用date-time模块创建闹钟,然后用playsound库播放声音。
from datetime import datetime
from playsound import playsound
alarm_time = input("Enter the time of alarm to be set:HH:MM:SS\n")
alarm_hour=alarm_time[0:2] alarm_minute=alarm_time[3:5]
alarm_seconds=alarm_time[6:8] alarm_period = alarm_time[9:11].upper()
print("Setting up alarm..")
while True:
now = datetime.now()
current_hour = now.strftime("%I")
current_minute = now.strftime("%M")
current_seconds = now.strftime("%S")
current_period = now.strftime("%p")
if(alarm_period==current_period):
if(alarm_hour==current_hour):
if(alarm_minute==current_minute):
if(alarm_seconds==current_seconds):
print("Wake Up!")
playsound('audio.mp3') ## download the alarm sound from link
break
四、石头剪刀布游戏
创建一个石头剪刀布的游戏,游戏者与与计算机PK。如果游戏者赢了,得分就会添加,看谁最终的得分最高。
提示:先判断游戏者的选择,然后与计算机的选择进行比较。计算机的选择是从选择列表中随机选取的。如果游戏者获胜,则增加1分。
import random
choices = ["Rock", "Paper", "Scissors"]
computer = random.choice(choices)
player = False
cpu_score = 0
player_score = 0
while True:
player = input("Rock, Paper or Scissors?").capitalize()
# 判断电脑与游戏者的选择
if player == computer:
print("Tie!")
elif player == "Rock":
if computer == "Paper":
print("You lose!", computer, "covers", player)
cpu_score+=1
else:
print("You win!", player, "smashes", computer)
player_score+=1
elif player == "Paper":
if computer == "Scissors":
print("You lose!", computer, "cut", player)
cpu_score+=1
else:
print("You win!", player, "covers", computer)
player_score+=1
elif player == "Scissors":
if computer == "Rock":
print("You lose...", computer, "smashes", player)
cpu_score+=1
else:
print("You win!", player, "cut", computer)
player_score+=1
elif player=='E':
print("Final Scores:")
print(f"CPU:{cpu_score}")
print(f"Plaer:{player_score}")
break
else:
print("That's not a valid play. Check your spelling!")
computer = random.choice(choices)
五、提醒小工具
利用Python一个提醒小工具,在设定好的时间在桌面做提醒通知。
提示:跟踪提醒时间可以用Time模块,显示桌面通知可以用toastnotifier库。
安装:win10toast
from win10toast import ToastNotifier
import time toaster = ToastNotifier()
try:
print("Title of reminder")
header = input()
print("Message of reminder")
text = input()
print("In how many minutes?")
time_min = input()
time_min=float(time_min)
except:
header = input("Title of reminder\n")
text = input("Message of remindar\n")
time_min=float(input("In how many minutes?\n"))
time_min = time_min * 60 print("Setting up reminder..")
time.sleep(2)
print("all set!")
time.sleep(time_min)
toaster.show_toast(f"{header}", f"{text}", duration=10, threaded=True)
while toaster.notification_active():
time.sleep(0.005)
【----相关技术讨论,Python入门基础教程文末见晓!----】
六、文章朗读器
用Python编写一个脚本,实现自动从提供的链接读取文章的功能。
import pyttsx3
import requests
from bs4 import BeautifulSoup
url = str(input("Paste article url\n"))
def content(url):
res = requests.get(url)
soup = BeautifulSoup(res.text,'html.parser')
articles = []
for i in range(len(soup.select('.p'))):
article = soup.select('.p')[i].getText().strip()
articles.append(article)
contents = " ".join(articles)
return contents
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
def speak(audio):
engine.say(audio)
engine.runAndWait()
contents = content(url)
## print(contents)
## In case you want to see the content
#engine.save_to_file
#engine.runAndWait()
## In case if you want to save the article as a audio file `
七、飞扬的小鸟
①游戏介绍:
《flappy bird》是一款由来自越南的独立游戏开发者Dong Nguyen所开发的作品,游戏于2013年5月24日上线,并在2014年2月突然暴红。
游戏规则:
游戏玩法非常简单,通过点击屏幕,使小鸟一直飞并穿过水管的空隙。虽然玩法简单,但是却具有一定的难度,因为要一直控制小鸟飞在适合的高度,以避开障碍。
这篇文章呢,就来分析这个游戏的原理,以及用python做一个简易版的FlappyBird。
②实现效果:
③源码分享:
#itbaizhan
import pygame
import sys
import random
class Bird(object): """定义一个鸟类"""
def __init__(self): """定义初始化方法"""
self.birdRect = pygame.Rect(65, 50, 50, 50) # 鸟的矩形
# 定义鸟的3种状态列表
self.birdStatus = [pygame.image.load("images/0.png"),
pygame.image.load("images/2.png"),
pygame.image.load("images/dead.png")]
self.status = 0
# 默认飞行状态
self.birdX = 120
# 鸟所在X轴坐标,即是向右飞行的速度
self.birdY = 350
# 鸟所在Y轴坐标,即上下飞行高度
self.jump = False
# 默认情况小鸟自动降落
self.jumpSpeed = 10
# 跳跃高度
self.gravity = 5
# 重力
self.dead = False
# 默认小鸟生命状态为活着
def birdUpdate(self):
if self.jump:
# 小鸟跳跃
self.jumpSpeed -= 1
# 速度递减,上升越来越慢
self.birdY -= self.jumpSpeed # 鸟Y轴坐标减小,小鸟上升
else: # 小鸟坠落
self.gravity += 0.1 # 重力递增,下降越来越快
self.birdY += self.gravity # 鸟Y轴坐标增加,小鸟下降
self.birdRect[1] = self.birdY # 更改Y轴位置
class Pipeline(object): """定义一个管道类"""
def __init__(self): """定义初始化方法"""
self.wallx = 400 # 管道所在X轴坐标
self.pineUp = pygame.image.load("images/top.png")
self.pineDown = pygame.image.load("images/bottom.png")
def updatePipeline(self): """"管道移动方法"""
self.wallx -= 5 # 管道X轴坐标递减,即管道向左移动
# 当管道运行到一定位置,即小鸟飞越管道,分数加1,并且重置管道
if self.wallx < -80:
global score
score += 1
self.wallx = 400
def createMap(): """定义创建地图的方法"""
screen.fill((255, 255, 255)) # 填充颜色
screen.blit(background, (0, 0)) # 填入到背景
screen.blit(Pipeline.pineUp, (Pipeline.wallx, -300)) # 上管道坐标位置
screen.blit(Pipeline.pineDown, (Pipeline.wallx, 500)) # 下管道坐标位置
Pipeline.updatePipeline() # 管道移动
# 显示小鸟
if Bird.dead:
# 撞管道状态
Bird.status = 2
elif Bird.jump:
# 起飞状态
Bird.status = 1
screen.blit(Bird.birdStatus[Bird.status], (Bird.birdX, Bird.birdY))
# 设置小鸟的坐标
Bird.birdUpdate()
# 鸟移动
# 显示分数
screen.blit(font.render('Score:' + str(score), -1, (255, 255, 255)), (100, 50))
# 设置颜色及坐标位置
pygame.display.update()
# 更新显示
def checkDead():
# 上方管子的矩形位置
upRect = pygame.Rect(Pipeline.wallx, -300,
Pipeline.pineUp.get_width() - 10,
Pipeline.pineUp.get_height())
# 下方管子的矩形位置
downRect = pygame.Rect(Pipeline.wallx, 500,
Pipeline.pineDown.get_width() - 10,
Pipeline.pineDown.get_height())
# 检测小鸟与上下方管子是否碰撞
if upRect.colliderect(Bird.birdRect) or downRect.colliderect(Bird.birdRect):
Bird.dead = True
# 检测小鸟是否飞出上下边界
if not 0 < Bird.birdRect[1] < height:
Bird.dead = True
return True
else:
return False
def getResutl():
final_text1 = "Game Over"
final_text2 = "Your final score is: " + str(score)
ft1_font = pygame.font.SysFont("Arial", 70)
# 设置第一行文字字体
ft1_surf = font.render(final_text1, 1, (242, 3, 36))
# 设置第一行文字颜色
ft2_font = pygame.font.SysFont("Arial", 50)
# 设置第二行文字字体
ft2_surf = font.render(final_text2, 1, (253, 177, 6))
# 设置第二行文字颜色
screen.blit(ft1_surf, [screen.get_width() / 2 - ft1_surf.get_width() / 2, 100])
# 设置第一行文字显示位置
screen.blit(ft2_surf, [screen.get_width() / 2 - ft2_surf.get_width() / 2, 200])
# 设置第二行文字显示位置
pygame.display.flip()
# 更新整个待显示的Surface对象到屏幕上
if __name__ == '__main__': """主程序"""
pygame.init()
# 初始化pygame
pygame.font.init()
# 初始化字体
font = pygame.font.SysFont("ziti.ttf", 50)
# 设置字体和大小
size = width, height = 400, 650
# 设置窗口
screen = pygame.display.set_mode(size)
# 显示窗口
clock = pygame.time.Clock()
# 设置时钟
Pipeline = Pipeline()
# 实例化管道类
Bird = Bird()
# 实例化鸟类
score = 0
while True:
clock.tick(30)
# 每秒执行30次
# 轮询事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if (event.type == pygame.KEYDOWN or event.type == pygame.MOUSEBUTTONDOWN) and not Bird.dead:
Bird.jump = True
# 跳跃
Bird.gravity = 5
# 重力
Bird.jumpSpeed = 5
# 跳跃速度,可以自己设置,控制速度
background = pygame.image.load("images/background.png")
# 加载背景图片
if checkDead():
# 检测小鸟生命状态
getResutl()
# 如果小鸟死亡,显示游戏总分数
else:
createMap()
# 创建地图
pygame.quit()
八、Python吃豆豆小游戏
九、Python中国象棋
十、Python植物大战僵尸
最后这里免费分享给大家一份Python全台学习资料,包含视频、源码。课件,希望能帮到那些不满现状,想提升自己却又没有方向的朋友,也可以和我一起来学习交流呀。
编程资料、学习路线图、源代码、软件安装包等!【点击这里】领取!
① Python所有方向的学习路线图
,清楚各个方向要学什么东西
② 100多节Python课程视频
,涵盖必备基础、爬虫和数据分析
③ 100多个Python实战案例
,学习不再是只会理论
④ 华为出品独家Python漫画教程
,手机也能学习
⑤ 历年互联网企业Python面试真题
,复习时非常方便